mod_rewrite keeps adding .html for files

I have a redirect situation where the site is part dynamic and part generated .html files.

For example, mysite.com/homepage and mysite.com/products/42 are actually static html files

Whereas other URLs are dynamically generated, like mysite.com/cart

Both mysite.com and www.mysite.com are pointing to the same place. However I want to redirect all of the traffic from mysite.com to www.mysite.com.

I'm so close but I'm running into an issue where Apache is adding .html to the end of my URLs for anything where a static .html file exists - which I don't want.

I want to redirect this:

  http://mysite.com/products/42 

To this:

  http://www.mysite.com/products/42

But Apache is making it this, instead (because 42.html is an actual html file):

  http://www.mysite.com/products/42.html

I don't want that - I want it to redirect to www.mysite.com/products/42

Here's what I started with:

RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]

RewriteRule ^(.*)$ http://www.mysite.com/$1 [R=301,L]

I tried making the parameters and the .html optional, but the .html is still getting added on the redirect:

RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]

RewriteRule ^(.*)?(\.html)?$ http://www.mysite.com/$1 [R=301,L]

What am I doing wrong? Really appreciate it :)

Upvotes: 0

Views: 550

Answers (2)

Victor Nițu
Victor Nițu

Reputation: 1505

Maybe you should try looking at apache's mod_negotiation to get rid of the .html or any file extension?

Link: http://httpd.apache.org/docs/2.0/mod/mod_negotiation.html

Upvotes: 0

anubhava
anubhava

Reputation: 785621

Here is the code you will need in your .htaccess under DOCUMENT_ROOT:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## first add www to your domain for and hide .html extension
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ http://www.mysite.com%1 [R=301,L]

## add www to your domain for other URIs without .html extension
RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]
RewriteRule ^ http://www.mysite.com%{REQUEST_URI} [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f [NC]
RewriteRule ^ %{REQUEST_URI}.html [L]

Upvotes: 2

Related Questions