Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

proxy - How do i redirect WWW url to non www url in nginx?

I have an issue with my nginx configuration , i want to redirect www.yoursay.transport.nsw.gov.au to https://yoursay.transport.nsw.gov.au

Here is my configuration

server {
    listen 443 ssl;

    ssl_certificate /etc/letsencrypt/live/yoursay.transport.nsw.gov.au/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yoursay.transport.nsw.gov.au/privkey.pem;

    # enable OCSP stapling to speed up first connect
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/yoursay.transport.nsw.gov.au/chain.pem;

    if ($host = www.$server_name) {
    rewrite ^(.*) https://$server_name$request_uri? permanent;
    }
    server_name yoursay.transport.nsw.gov.au;

    root /var/www/ehq;

    add_header X-XSS-Protection "1; mode=block";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload";

    include snippets/common_blocks.inc;
}

server {
    listen 80;

    server_name yoursay.transport.nsw.gov.au;
    return 301 https://yoursay.transport.nsw.gov.au$request_uri;
}

But still it doesnt works , it says ERR_CONNECTION_CLOSED

Please help me out to fix this issue .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Replace this:

    if ($host = www.$server_name) {
    rewrite ^(.*) https://$server_name$request_uri? permanent;
    }
    server_name yoursay.transport.nsw.gov.au;

with this:

    if ($host = www.yoursay.transport.nsw.gov.au) {
        return 301 https://yoursay.transport.nsw.gov.au$request_uri;
    }
    server_name yoursay.transport.nsw.gov.au www.yoursay.transport.nsw.gov.au;

Explanation:

When someone visit your website they sent HTTP request headers. One of them is Host which is the address they've used to reach the website. It can be an IP-address, www.example.com, example.com, or something.completely.irrelevant. server_name option defines to which Host headers this configuration belong. That is why I added www.yoursay.transport.nsw.gov.au to server_name, so this configuration is used for visitors accessing the address. You may also wish to repeat this in your HTTP server block (the one listening on port 80).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...