Search code examples
wordpress.htaccessmod-rewritehttp-status-code-404trailing-slash

How to configure .htaccess file for rewrite rules to get rid of extensions, trailing slashes, www?


This is what I want -

When somebody enters site.com/page.php or site.com/page or site.com/page/ , all should work the same, and the url displayed in the address bar should be site.com/page [ I don't like extensions and trailing slashes ]

I also want to get rid of the www from the url bar, as it's unnecessary.

This is my current .htaccess files Rewrite rules -

RewriteEngine on
RewriteCond %{HTTP_HOST} ^site\.com
RewriteRule ^(.*)$ http://www.site.com/$1 [R=permanent,L] 

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

This solves the www and the extension issue, but not the trailing slash one!

But, more importantly, I recently installed WordPress at site.com/blog, but whenever I try to access that, I am redirected to the 404 page instead. It works when I remove all the Rewrites!

Have I messed up my rewrites? I am not a regular expressions ninja!


Solution

  • Try adding the following to the top of your existing .htaccess file, above any existing rules e.g. Wordpress rules.

    RewriteEngine on
    RewriteBase /
    
    #if the host is not site.com, e.g www.site.com
    RewriteCond %{HTTP_HOST} !^site\.com$ [NC]
    #then redirect to site.com e.g to remove the www
    RewriteRule ^(.*)$ http://site.com/$1 [R=301,L] 
    
    #if the URL ends with a slash
    RewriteCond %{REQUEST_URI} ^/(.+)/$
    #redirect to URL without slash
    RewriteRule . http://site.com/%1 [R=301,L] 
    
    #skip wordpress site which starts with blog
    RewriteCond %{REQUEST_URI} !^/blog [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [NC,L]