Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I would like to ask for some help with the following Nginx configuration, so that URLs such as https://www.mywebsite.com get rewritten as https://mywebsite.com. I am currently using the following configuration:

server {
    server_name www.mywebsite.com;
    return 301 $scheme://mywebsite.com$request_uri;
}
server {
    listen 80;
    server_name mywebsite.com;

    # Some more settings...
}
server {
    listen 443 ssl;
    server_name mywebsite.com;

    ssl_certificate path_to_ssl_certificate;
    ssl_certificate_key path_to_ssl_certificate_key;

    # Some more settings...
}

In case that matters, the certificate I am using is a wildcard SSL certificate that was self-signed using OpenSSL on the server itself (Ubuntu 12.04). What is happening is that www.mywebsite.com correctly redirects to mywebsite.com, but https://www.mywebsite.com does not redirect to https://www.mywebsite.com (i.e., the www still appears when viewing the page in a browser). What can I be doing wrong?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

The solution is fixing first server block to this:

server {
    listen 80;
    listen 443;
    server_name www.mywebsite.com;
    return 301 $scheme://mywebsite.com$request_uri;
}

E.g. you forgot to catch www.mywebsite.com connections on ssl port, that's all. By the way, it's the best way to remove www from site name, good choice.

share|improve this answer

Your redirect happens in a virtual host only listening on port 80. To redirect requests coming in over SSL you need a virtual host listening on port 443 with SSL. Unless your browsers all support SNI, you can only have one SSL virtual host, and so the rule needs to go into your existing SSL server block.

if ($host = www.mywebsite.com) {
    rewrite ^ https://mywebsite.com$request_uri? permanent;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.