Nginx Vhosts with SSL

r3wt asked:

I have 3 domains running on an nginx server with ssl

i have sni enabled, and am using a vhost for each site.

the host records for the site are all like this

A Record: @ <IP ADDRESS> 1800
A Record: www <IP ADDRESS> 1800

the conf files are all like this. and do their job as intended pretty much except one problem(i’ll expand on this in a moment, now i will explain the configuration file you see below)

step 1 server_name (the first comment) redirects www traffic to non-www

step 2 server_name redirects http:// traffic on port 80 to https://

step 3 server_name is the actual server code for serving pages over ssl from port 443.

log_format  '$remote_addr - $remote_user [$time_local] "$request" '
             '$status $body_bytes_sent "$http_referer" '
             '"$http_user_agent" $http_x_forwarded_for';

#redirects www traffic to

server {
    rewrite ^(.*)$1 permanent;

#redirect http traffic to https
server {
        listen   80;
        return 301 https://$server_name$request_uri;

#server and ssl configuration.       
server {
        listen   443;
        index index.php;
        root  /home/wwwroot/;
        ssl on;
        #enables SSLv3/TLSv1, but not SSLv2 which is weak and should no longer be used.
        ssl_protocols SSLv3 TLSv1.2;
        #Disables all weak ciphers
        ssl_ciphers ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM;
        ssl_certificate /usr/local/nginx/ssl/domains/;
        ssl_certificate_key /usr/local/nginx/ssl/domains/;

        include other.conf;
        location ~ .*\.(php|php5)?$
                try_files $uri =404;
                fastcgi_pass  unix:/tmp/php-cgi.sock;
                fastcgi_index index.php;
                include fcgi.conf;
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
                expires      30d;

        location ~ .*\.(js|css)?$
                expires      12h;

        access_log  /home/wwwlogs/;
        error_page   404  =  /access_denied.php;
        error_page   403  =  /access_denied.php;

the problem redirects to redirects to redirects to <<< Doh! wtf??? >>>

Note: this problem only exists with www the redirect works fine with out it.

please help, this thing has been bugging me for days, i’ve jumbled my configuration files around rebooted my server, reissued my ssl certificates, and no matter what it always results in error. why?

My answer:

Your HTTP to HTTPS redirect is subtly wrong:

        return 301 https://$server_name$request_uri;

This uses the server name defined in the server block, which is probably not what you want, especially when you are using a single server block to redirect several domains.

Instead, use:

        return 301 https://$http_host$request_uri;

Which will use the domain provided by the client.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.