500 internal server error (working on ubuntu)

apache-2.2

I copied my printenv.pl file into /usr/lib/cgi-bin and ran:

chmod +rx printenv.pl

In my apache2.conf file, I added the following lines:

<Files ~ "\.pl$">
    Options +ExecCGI
</Files>

AddHandler cgi-script .pl

And restarted the Apache server:

/etc/init.d/apache2 start

But when I go to http://localhost/cgi-bin/printenv.pl I get the following error:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.

Apache/2.2.17 (Ubuntu) Server at localhost Port 80

Here's my error log file:

[Thu Jul 28 19:28:43 2011] [error] [client 127.0.0.1] (2)No such file or directory: exec of '/usr/lib/cgi-bin/printenv.pl' failed
[Thu Jul 28 19:28:43 2011] [error] [client 127.0.0.1] Premature end of script headers: printenv.pl

But this is what my /usr/lib/cgi-bin directory looks like:

/usr/lib/cgi-bin$ ls -l
total 8
-rwxr-xr-x 1 root root 331 2011-07-28 19:01 printenv.pl
-rwxr-xr-x 1 root root 335 2011-07-28 18:50 printenv.pl~

Can you please help me fix this… thanks!

Best Answer

Double-check the first line of your script.

If the line does not begin with #! or perl is installed in a different location than the path following the #! (e.g., /usr/local/bin/perl vs /usr/bin/perl), you will get that error.

If the path to perl appears correct, and you've copied over the script from a Windows machine, you may be being tripped up by a carriage return character at the end of the line.

You can use cat -v /usr/lib/cgi-bin/printenv.pl | head -1 to verify that there isn't a ^M at the end of the line.

If there is, you can use perl -pi.bak -e 's/\r+$//' /usr/lib/cgi-bin/printenv.pl to remove it.