2

So I have an application running that for legacy reasons must keep it's old url with a trailing port number working.

So I have a configuration similar to this:

server {
        listen 443 ssl;
        listen 8080 ssl;
        server_name myurl.com;

        ssl                     on;
        ssl_certificate         /etc/nginx/conf.d/certfile.pem;
        ssl_certificate_key     /etc/nginx/conf.d/keyfile.key;
        ssl_session_timeout     5m;
        ssl_session_cache       shared:SSL:10m;
        ssl_protocols           TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers             HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers   on;

        location / {

        proxy_pass              http://127.0.0.1:7990;
        proxy_http_version      1.1;
        proxy_set_header        Host $host;
        proxy_set_header        X-Forwarded-Host $host;
        proxy_set_header        X-Forwarded-Server $host;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        Location $host:443;
        proxy_redirect          off;
        }

}

It is working fine exept for the fact that some AJAX request made from myurl.com:8080 will throw CRSF errors. I would like to make it so that when a user connect with 8080 port, nginx will rewrite it to 443 automatically. Is this possible to do? I have tried adding various headers but none of them seemed to do the trick.

Also tried to do a return 301 https://$server_name:443$request_uri; but nginx did not like it really.

1 Answer 1

4

You could break the server block into two, one for each port. Move common configuration into the outer block (if these are the only server blocks you have) or include common configuration with an include directive.

For example:

ssl_certificate         /etc/nginx/conf.d/certfile.pem;
ssl_certificate_key     /etc/nginx/conf.d/keyfile.key;
ssl_session_timeout     5m;
ssl_session_cache       shared:SSL:10m;
ssl_protocols           TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers             HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers   on;

server {
    listen 8080 ssl;
    server_name myurl.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name myurl.com;

    location / { ... }
}

The return directive does not need a port specification if the https port is 443. If nginx insists on adding port 8080, try adding a port_in_redirect off; statement.

1
  • Just tried this my self before reading it. Seems that I got it working finally. The common directive for SSL conf is a +1. Thank you!
    – inimene
    Sep 12, 2016 at 15:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .