0

I would like all traffic without the www, including https, to be redirected to the respective url with the www.

So http://example.com -> http://www.example.com, https://example.com -> https://www.example.com

There's plenty of info online about forcing ssl, which I do not want to do, and forcing www, but only for http. Just adding an s and changing the listen 80 -> listen 443 breaks the http sites. Here's my config so far:

 server { listen 80; server_name example.com; location / { rewrite ^/(.*)$ http://www.example.com/$1 permanent; } } server { listen 80; server_name www.example.com; root /opt/example; index index.html; <locations stuff> } server { listen 443; server_name example.com; ssl on; ssl_certificate /opt/nginx/ssl/server.crt; ssl_certificate_key /opt/nginx/ssl/server.key; location / { rewrite ^/(.*)$ https://www.example.com/$1 permanent; } } server { listen 443; server_name www.example.com; root /opt/example; ssl on; ssl_certificate /opt/nginx/ssl/server.crt; ssl_certificate_key /opt/nginx/ssl/server.key; <locations stuff> } 
2
  • Adding an s where? Breaks the http sites how? Commented Oct 23, 2011 at 4:43
  • Sorry adding an s after http in the rewrite rule. Basically it does not respond to http requests. Commented Oct 23, 2011 at 5:00

1 Answer 1

3

This is a stripped down version of my own config, which I think does what you want:

server { listen 80 default; listen 443 default ssl; server_name *.example.com; if ($host = example.com) { rewrite ^(.*) $scheme://www.example.com$1 permanent; } root /opt/example; ssl on; ssl_certificate /opt/nginx/ssl/server.crt; ssl_certificate_key /opt/nginx/ssl/server.key; } 
1
  • i was looking for this way of doing it thanks, i like it because you only use one server block Commented Jan 21, 2013 at 7:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.