'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?
Solution 1:[1]
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>
Solution 2:[2]
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
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bumbleshoot |
| Solution 2 | |
| Solution 3 |
