.htaccess rewrite requests for file-name URLs to corresponding permalink URLs

Viewed 88

I have a question about my .htaccess-code. It is doing the following:

  1. Adding a trailing slash to every URL
  2. Removing the .php file extension.

This works, so if I type domain.com/page/, the browser shows the content of domain.com/page.php. If I type domain.com/page (without the trailing slash), the browser redirects to domain.com/page/.

BUT if I type domain.com/page.php the browser does not redirect to domain.com/page/.

Is there a way to redirect the request domain.com/page.php to domain.com/page/?

Here's my current .htaccess-code:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !(^$|\.[a-zA-Z0-9]{1,5}|/)$ %{REQUEST_URI}/ [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^((/?[^/]+){1,2})/$ $1.php [L]

Thank you for your help!

1 Answers

With your shown samples, could you please try following. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
##First 2 rules are added by OP itself.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !(^$|\.[a-zA-Z0-9]{1,5}|/)$ %{REQUEST_URI}/ [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^((/?[^/]+){1,2})/$ $1.php [L]

##Newly added rule for removing .php from browser if .php is hit in it.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]
Related