non WWW to WWW url rewrite - Confused with some syntax

Hi,

I have a question about rewriting non WWW urls to WWW urls…

I have acomplished this with:

server {
    listen        80;
    server_name   mydomain.com;
    rewrite ^(.*) http://www.mydomain.com$1 permanent;
    }

It works BUT what is the difference with this syntax:

server {
    listen        80;
    server_name   mydomain.com;
    rewrite ^/(.*) http://www.mydomain.com/$1 permanent;
    }

On the second example there are two slash symbols / added inside the syntax and it seems the second syntax gives the same result.

But which one is correct to use???

The first syntax without the slash symbols or the second syntax with the slash symbols included? Is there any difference in usability or in the produced result? It looks they work the same but maybe there is something that i dont see.

Thanks for any help

George

4 Replies

sry, mis-read post - deleted

They're both fine,

the first one means take whatever is after mydomain.com and append it to www.mydomain.com then redirect.

The second one means take whatever is after the / after mydomain.com and append it to www.mydomain.com/ and redirect.

However, the second one will not redirect "http://mydomain.com" since it doesn't end with a slash.

Here's some other options…

It may be more correct to do:

server {
   listen        80;
   server_name   .mydomain.com;
   if ($host != 'www.mydomain.com' ) {
      rewrite ^(.*) http://www.mydomain.com$1 permanent;
   }
} 

Or an example if found to achieve the same:

server {
  listen          80;
  server_name     domain.com *.domain.com;
  rewrite ^       http://www.domain.com$request_uri permanent;
 }
server {
  listen          80;
  server_name     www.domain.com;
  index           index.html;
  root            /home/domain.com
}

@RoryH:

Here's some other options…

It may be more correct to do:

Or an example if found to achieve the same:

server {
  listen          80;
  server_name     domain.com;
  rewrite ^       http://www.domain.com$request_uri permanent;
 }
server {
  listen          80;
  server_name     www.domain.com;
  index           index.html;
  root            /home/domain.com
}

I like that, no regex, immeasurably quicker.

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct