Saturday, April 9, 2022

[SOLVED] Apache - remove .php and .html file extensions using mod_rewrite in httpd.conf

Issue

Running Apache 2 on Ubuntu 14.04. rewrite_module is enabled (sudo apachectl -M).

In /etc/apache2/apache2.conf (the Ubuntu version of httpd.conf) I have the following code block:

<Directory /var/www/>
    <IfModule mod_rewrite.c>
        RewriteEngine On

        RewriteCond /%{REQUEST_FILENAME}.php -f
        RewriteRule ^([a-zA-Z0-9_-\s]+)/$ /$1.php

        RewriteCond /%{REQUEST_FILENAME}.html -f
        RewriteRule ^([a-zA-Z0-9_-\s]+)/$ /$1.html
    </IfModule>

    <IfModule mod_expires.c>
        ...

        <IfModule mod_headers.c>
            ...
        </IfModule>
    </IfModule>
</Directory>

Ran sudo service apache2 restart.

When I visit a url on my server without the .php file extension, I get a 404! Why isn't this working?


Solution

I finally figured it out. What worked for me was this:

<Directory /var/www/>
    <IfModule mod_rewrite.c>
        RewriteEngine On

        RewriteCond %{REQUEST_FILENAME}.php -f
        RewriteRule ^(.*)$ $1.php [L]

        RewriteCond %{REQUEST_FILENAME}.html -f
        RewriteRule ^(.*)$ $1.html [L]
    </IfModule>

    <IfModule mod_expires.c>
        ...

        <IfModule mod_headers.c>
            ...
        </IfModule>
    </IfModule>
</Directory>


Answered By - bumbleshoot
Answer Checked By - Willingham (WPSolving Volunteer)