1

I'm having an issue where if a user types:

www.myurl.com/page.html

they are redirected first to

myurl.com/page.html

and then to

myurl.com/page

This is because I have the following in my conf file

    #remove www from url
    if ($host ~* ^www\.(.*)) {
        set $remove_www $1; 
        rewrite ^(.*)$ http://$remove_www$1 permanent;
    }

    location  /{

            # removes .html extension
            if ($request_uri ~ \.html($|\?)) {
                    rewrite ^(.+)\.html$ $1 permanent;
            }
    }

My question:

Is there a way to eliminate the the first redirect so that if a users types www.mysite.com/page.html they are redirected straight to mysite.com/page

jwerre
  • 748
  • 3
  • 11
  • 26
  • Is your question not answered by [Everything you ever wanted to know about mod_rewrite rules but were afraid to ask](http://serverfault.com/questions/214512)? (Hint: nginx rewrite rules are very similar to Apache rewrite rules - It's just regular expressions: `$1` is the first thing in parentheses, `$2` is the second, `$3` the third... :-) – voretaq7 Feb 19 '13 at 20:44

1 Answers1

2

You need your www. rule to strip the .html if present. You also shouldn't need the if statement in the second rewrite:

#remove www from url
if ($host ~* ^www\.(.*)) {
    set $remove_www $1; 
    rewrite ^(.*?)(\.html)?$ http://$remove_www$1 permanent;
}

location / {
    rewrite ^(.+)\.html$ $1 permanent;
}
mgorven
  • 30,036
  • 7
  • 76
  • 121