Junji Zhi Junji Zhi - 2 months ago 18
HTTP Question

Nginx: redirect custom domain http requests to https

We want to redirect

something.custom.com
http requests to https, leaving the other requests unchanged. Tried something like below, but it didn't work:

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

server_name _;

if ($host ~ ^(.*?)\.custom\.com) {
return 301 https://$host$request_uri;
}

root /www/example/public;
}

server {
listen 443 default_server ssl;
listen [::]:443 default_server ipv6only=on ssl;

server_name _;

root /www/example/public;
}


Is there something wrong with my setup?

Answer

As stated in the comments, the configuration below should work:

server {
    listen 80;
    listen [::]:80 ipv6only=on;

    server_name something.custom.com;
    return 301 https://something.custom.com$request_uri;
}

server {
    listen 80 default_server;
    server_name _;

    #Rest of your config here
}

server {
    listen 443 default_server ssl;
    listen [::]:443 default_server ipv6only=on ssl;

    server_name _;

    root /www/example/public;
}