slug: use-nginx-to-redirect-www-to-subdomain-under-https datepublished: 2017-09-10T05:47:48 dateupdated: 2017-12-30T07:46:24 tags: Tech Ideas, English Posts excerpt: "How to redirect from https to https; 443 ssl.had a big struggle a few days ago when tring to organize the re-direct between different domain name of by blog. Essentially, I want everything to go through non-www https route –– namely, https://blog.moelf.xyz" –-

So I had a big struggle a few days ago when tring to organize the re-direct between different domain name of by blog. Essentially, I want everything to go through non-www https route –– namely, https://blog.moelf.xyz

That means:

Doing the http -> https 301 redirect is super easy in nginx:

Simply have a server block in /etc/nginx/**.conf :

server{ server_name moelf.xyz blog.moelf.xyz; listen 80; return 301 https://blog.moelf.xyz; #rest of your block; }

will do the job. This basically means anything coming to port 80 on your server will get redirected to https non-www domain.

The https part is tricky: if you want your https non-www to be resolved normally, you will need SSL certificates for both non-www and www seperately (in my case blog.**.xyz) because the website is directing the browser from https to https.

server { server_name moelf.xyz blog.moelf.xyz; listen 80; return 301 https://blog.moelf.xyz/; } server { listen 443 ssl; server_name moelf.xyz; return 301 https://blog.moelf.xyz/; ssl_certificate ***/fullchain.pem; ssl_certificate_key ***/moelf.xyz/privkey.pem; #other_stuff_in_the_block } server { server_name blog.moelf.xyz; # Replace with your domain listen 443 ssl; access_log /var/log/nginx/www_ss.log; ssl_certificate ***/blog.moelf.xyz/fullchain.pem; ssl_certificate_key ***/blog.moelf.xyz/privkey.pem; #other_stuff_in_the_block }

In the above code, the second block is used to redirect non-www visit and the third server block is used to handle everything.