mod_rewrite Remove .php not working
RewriteEngine on
RewriteCond %{http_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
The first rule is working so it's correctly redirecting the browser. However, the second rule which should be stripping .php so that visitors can go to domain.com/services instead of domai开发者_如何学Pythonn.com/services.php is not working. The third condition which adds a / to the end, works.
Any idea why stripping .php gives me a 404 error:
The requested URL /s/p/domain.com/public/packing-tips.php was not found on this server?
Any advice?
try this dear:
RewriteRule ^([^/]+)/$1
hope will help you.
Please try removing this line and check again:
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteEngine on
# force canonical name
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,QSA]
# Add .php to requested resource (if such php file does exist)
# e.g. www.example.com/services/ => www.example.com/services.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)/$ /$1.php [QSA,L]
# Force trailing slash to be present (only if such file does not exist)
# e.g. www.example.com/services => www.example.com/services/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*[^/])$ /$1/ [R=301,QSA]
If you request this URL domain.com/services
it will be redirected to domain.com/services/
if such file/folder does not exist. Then, if (ONLY IF) domain.com/services.php
is does exist, it will be rewritten to domain.com/services.php
. If there is no such php file, then you should see 404 error.
In theory you could add these lines after "force canonical name" rule, then you can get rid of few RewriteCond rules later (useful if you have quite a bit rewrite rules), but you have to verify this on your site -- it works fine for me, but you may have specific circumstances:
# Do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]
For stripping out .php extension use this .htaccess code:
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{THE_REQUEST} ^GET\s.+\.php [NC]
RewriteRule ^(.+)\.php$ /$1 [NE,R=301,L,NC]
RewriteCond %{REQUEST_URI} !\.php$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [L]
精彩评论