4

I'm trying to remove .php from my URLs and add a trailing slash to the end. I've got the .php removal working just fine, but I'm struggling to get the trailing slash working.

Here's what I've got so far:

# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## hide .php extension snippet

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

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

Thanks in advance!

1
  • Please elaborate on get the trailing slash working. What URL do you request in your browser? How is it handled? How do you want it to be handled? Commented Feb 7, 2014 at 11:06

2 Answers 2

17

First of all that code and comments look very familiar :)

Use this code:

RewriteEngine On
RewriteBase /

## hide .php extension snippet

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

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

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

4 Comments

Anubhava I don't suppose you know how I could make the .php to non .php redirect work as a 301 do you? Currently it's a 302 which isn't ideal for SEO if we have any links going to the .php versions of the URLs.
Just change first rule to have this flag: [R=301,L] and SEO will be taken care of.
This works great. I'm running into an issue, however, where my contact form that uses PHP mailer is now seeing GET as the request method instead of POST. Any idea what might be wrong with my config?
These rules cannot change POST to GET. Try using R=308 instead of R=301 if you're using POST.
3

Try this one:

# Run PHP without filename extension
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php

# Return 404 if original request is *.php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]

Comments

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.