Home > Software design >  Error 404 being given on a virtaul host with custom .htaccess file
Error 404 being given on a virtaul host with custom .htaccess file

Time:12-03

I have an apache2 installation on my local linux server. It has a virtual host called pcts.local which has the root /var/www/repos/pcts/. Inside the root of pcts.local is a .htaccess file which attempts to rewrite urls to include .php if it isn't given like below:

http://pcts.local/ -> http://pcts.local/index.php
http://pcts.local/contact -> http://pcts.local/contact.php

The problem is, http://pcts.local/contact gives an error 404 but http://pcts.local/contact.php gives 200.

Virtual Host Configuration:

<VirtualHost *:80>
        ServerName pcts.local
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/repos/pcts

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

.htaccess file in /var/www/repos/pcts/

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(. )$ $1.php [NC,L]

Thanks in advance of any help!

CodePudding user response:

In your code, REQUEST_FILENAME is expecting a file with a php extension to perform the rewrite.

Try this instead:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.] )$ $1.php [NC,L]

CodePudding user response:

<VirtualHost *:80>
    ServerName pcts.local
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/repos/pcts

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

If this is your complete config then your .htaccess file is not being processed.

You've not enabled .htaccess overrides for the specific directory. (ie. You've not enabled the parsing of .htaccess files.) .htaccess overrides are disabled by default.

However, you've not enabled access to this area of the filesystem either? Have you done this elsewhere in the server config?!

You should have a relevant <Directory> section like the following inside the <VirtualHost> container:

<Directory /var/www/repos/pcts>
    # Enable .htaccess overrides
    AllowOverride All

    # Allow user access to this directory
    Require all granted
</Directory>

You can restrict .htaccess overrides further if required (see the reference link below)

Reference:

  • Related