简体   繁体   中英

Override nginx default 80 rule with SSL redirect rule

I try to override nginx rules thinking what comes last replaces conflicting rules above them. In my case, I expect all insecure requests via HTTP should become HTTPS and reach the server that runs on 8000.

  • However, on hitting HTTP version, the welcome page is rendered which is from default.conf .
  • Is there a way to override it? Otherwise is it safe to comment out default.conf?
  1. Port 80 to 443 Redirect - not working
  2. Proxy pass 443 to 8000 - works

Default rules in /etc/nginx/conf.d/default.conf

server {
    listen       80 default_server;
    server_name  localhost;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

Custom rule in /etc/nginx/conf.d/sslredirect.conf

server {
    listen 80;
    server_name wconnector.com;
    return 301 https://$server_name$request_uri;
}

Another custom rule which works fine /etc/nginx/conf.d/wconnector.conf

server {
    listen 443 ssl;
    server_name wconnector.com;
    ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;

    location / {
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_pass    http://127.0.0.1:8000/;
    }
}

nginx -T lists out confs in the order: default.conf, sslredirect.conf, wconnector.conf.

The order of config files does not matter in nginx. When it comes to requests sent to port 80 in your config, the important part is the Host header.

Depending on the Host header the respective server directive processes the request. In case of http://wconnector.com the /etc/nginx/conf.d/sslredirect.conf server directive processes the request and shall properly redirect to https://wconnector.com

In case of any other host, the server directive in /etc/nginx/conf.d/default.conf processes the request since it specifies default_server in listen for port 80 .

If you don't need the /etc/nginx/conf.d/default.conf config file, it is safe to remove it altogether. nginx will start and process requests just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM