bumbleshoot
bumbleshoot

Reputation: 1160

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

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?

Upvotes: 0

Views: 2216

Answers (3)

greg
greg

Reputation: 21

Yup, I spent 2 hours trying everything until I deleted the leading slash on $1 (i.e. "$1" not "/$1"), then everything worked. Contrary to another user's comment. Although I did need the slash in the RewriteRule regex to match the requested filename, before I changed it to "^(.*)$" and first tested with a RewriteCond.

Upvotes: 0

bumbleshoot
bumbleshoot

Reputation: 1160

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>

Upvotes: 0

Amit Verma
Amit Verma

Reputation: 41239

Your rules work fine for me on htaccess context. But when I added those rules to serverConfig context The server returned a 404 not found. Actually the problem is that on serverConfig context a leading slash in RewriteRule's pattern is required . So you need to add a leading slash to your Rule's pattern :

RewriteRule ^/([a-zA-Z0-9_-\s]+)/?$ /$1.php

Upvotes: 0

Related Questions