4

I also want to 301 redirect any url that ends in .php. Then I internally redirect anything that ends in a / to the name before / plus .php. These both work fine when they are alone. But putting them in the same .htaccess I get a The page isn't redirecting properly.

What am I doing wrong here?

RewriteRule ^(.*)\.php$ /$1/ [R=301,L]

RewriteRule ^(.*)/$ $1.php [QSA,L]

1 Answer 1

5

These rules should work for you:

RewriteEngine On

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

## hide .php extension
# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1/ [R=301,L,NE]

# To internally forward /dir/file/ to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]
Sign up to request clarification or add additional context in comments.

1 Comment

This does work, thank you. Do you know how to force the trailing slash too it it isn't there when typed into the address bar?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.