How to enforce primary domain in nginx

To avoid duplicate content, it’s adviced that any given content on your site only has one URL.
If you, like me, have a website built in Express, then you probably have a hard time getting your primary domain to work.

But with nginx it’s pretty simple to work around that.
All you have to do is to create a new rule that takes all your secondary domains and rewrite them to your primary domain.

1
2
3
4
5
6
7
8
9
10
11
12
# This rule catches all trafic to 'www.martinnielsen.me'
# and redirects it to 'martinnielsen.me'
server {
listen 80;
server_name www.martinnielsen.me;
rewrite ^(.*) http://martinnielsen.me$1 permanent;
}
server {
listen 80;
server_name martinnielsen.me;
# all the other configuration goes here
}

Once you’ve made the change, you should restart your nginx service with sudo service nginx restart


Comments: