Redirecting Pages and Files with no extension to file/pages with an extension with .htaccess

After hours of searching unable to find the answer anywhere I finally figured it out!

I needed to 301 redirect files or pages like:

http://www.domain.com/directory/directory2/pagename

to

http://www.domain.com/directory/directory2/pagename.php (or .htm etc.)

Since most of files already had the .htm extension, mod-rewrite was looping itself making the redirect impossible. I only had about 100 pages that didn’t have the .htm extension so I need to add a line of code to check to see if the file name already exists before the Rewrite Rule.

How I finally got it to work was like this

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.htm -f
RewriteRule ^app/category/(.*)$ /app/category/$1.htm [R=301,L]

  • RewriteEngine on instructs mod_rewrite to start checking URLS.
  • The next line: RewriteCond %{REQUEST_FILENAME} !-d” instructs mod_rewrite to not do the redirect if the request is for an actual directory on the server. For example if your website hosts a blog in a sub directory called “blog” (http://www.domain.com/blog) you wouldn’t want /blog to redirect to /blog.htm
  • RewriteCond %{REQUEST_FILENAME}.htm -f” – tells mod-rewrite to not run the redirect on files that already exist on the server. For example you would want to redirect file.htm to file.htm.htm – this will cause a endless circle that will never end and prevent your pages from ever loading (the first mistake I made)
  • The next line “RewriteRule ^app/category/(.*)$ /app/category/$1.htm [R=301,L]” I’ve broken down below.
    • The “^” tells mod-rewrite to include everything before “app”.
    • The (.*) is a variable that matches any and all characters after the final “/” in my URL. The $ is how you end the command line.
    • The next portion “/app/category/$1.htm” tells mod-rewrite the URL to redirect to.
    • the “1$” is the variable used to tell mod-rewrite you are referring to the “(.*)” in the previous line.
    • [R=301,L] –  means Redirect=301 permanent redirect and “L” means “last rewrite to run”

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *