pythonapachehttpserverhttp-1.0

Apache Internal Server Error when posting basic HTTP/1.0 200 OK response in my server? Definitely printing newline


I'm getting an Internal Server error when printing this:

enter image description here

This is my code (python):

print "HTTP/1.0 200 OK\n\r",
print "Content-Type: text/html\n\r",
print "\n\r", 

The error log says:

malformed header from script 'bad_req.py': Bad header: HTTP/1.0 200 OK

I'm researched the issue and can't find any solutions. Any help would be really appreciated.


Solution

  • Yes, wrong end of lines definitely.

    You should have "\r\n", but also, you do not have to worry about that if you're using script as CGI.

    You can use only "\n" and everything will work.

    Also, I don't think Apache will let you choose protocol for it to use and thus you shouldn't use your first line:

    print "HTTP/1.0 200 OK"
    
    1. 200 OK is a status that will be returned back on a success anyway

    2. If you really do need to change status, use Status HTTP header, and Apache will adapt to it:

      print "Status: 400 Forbidden"

    Your script should look like:

    # If you want status :D
    print "Status: 200 Some nasty extra status"
    print "Content-Type: text/html\n"
    # End of headers
    print "<h1>Some HTML here</h1>"
    

    Note that I used "\n" only on last header, and nowhere else.

    That is because print adds "\n" automatically unless you tell it otherwise, but last header have to be separated from the body of document with two new lines "\r\n\r\n", that is why you should use it only on last header. It indicates end of headers.

    Or you can do:

    print "Content-Type: text/html"
    print
    

    Print with no args will print just "\n" and, as I said before, Apache will interpret them correctly as "\r\n"

    In your case your headers looked like this repr:

    """
    HTTP/1.0 200 OK
    
    \rContent-Type: text/html
    
    \r
    \r
    
    """
    

    Which is obviously a wrong header. :D

    If you aren't using script as CGI rules may differ but only slightly.

    If you have to enforce HTTP/1.0 behaviour then use header Connection header:

    print "Connection: close"
    

    although whether a connection will be closed remains upon the client and Apache's timeout. I am not sure whether the protocol will be changed to HTTP 1.0. Default is 1.1