NginX Rewrites

I'm happily running a site using Nginx. In my server conf I use:

server {

            listen   80;
            server_name  www.foo.com;
            rewrite ^/(.*) http://foo.com/$1 permanent;

           }

to strip the www part of the domain.

I also own the domain foo.co.uk. What I want to do is have visitors to foo.co.uk redirected to foo.com. So, would the following work or do I have to brush up on my Regex:

server {

            listen   80;
            server_name  foo.co.uk;
            rewrite ^/(.*) http://foo.com/$1 permanent;

           }

server {

            listen   80;
            server_name  www.foo.co.uk;
            rewrite ^/(.*) http://foo.com/$1 permanent;

           }

3 Replies

Your regex is the same in all cases

^/(.*)

which means "beginning of line, followed by a / and then rember everything else as $1. So "/hello/there" would make $1="hello/there". Your redirect then rewrites that as http://foo.com/$1 (so http://foo.com/hello/there) with a permanent redirect response in the HTTP headers.

You could also just put them all in the same server declaration:

server {

            listen   80;
            server_name  www.foo.com foo.co.uk www.foo.co.uk;
            rewrite ^/(.*) http://foo.com/$1 permanent;

           } 

Thanks guys. I'm liking the everything in the same declaration method. Implementing now.

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