Force www. and https in nginx.conf (SSL)

前端 未结 4 1322
梦谈多话
梦谈多话 2021-02-05 20:48

After purchasing a SSL certificate I have been trying to force all pages to secured https and to www.

https://www.exampl.com is working and secure but only if type it i

4条回答
  •  失恋的感觉
    2021-02-05 21:07

    The best way to implement WWW and HTTPS redirection is to create a new server section in Nginx config:

    server {
        listen      80;   #listen for all the HTTP requests
        server_name example.com www.example.com;
        return      301         https://www.example.com$request_uri;
    }
    

    You will also have to perform https://example.com to https://www.example.com redirection. This may be done with code similar to the following:

    server {
        listen              443 ssl;
        server_name         example.com;
    
        ssl_certificate     ssl.crt; #you have to put here...
        ssl_certificate_key ssl.key; #   ...paths to your certificate files
        return      301     https://www.example.com$request_uri;
    }
    

    And of course, you must reload Nginx config after each change. Here are some useful commands:

    check for errors in the configuration:

    sudo service nginx configtest
    

    reload configuration (this would be enough to make changes "work"):

    sudo service nginx reload
    

    restart the whole webserver:

    sudo service nginx restart
    

    Important note:

    All your server sections must be inside http section (or in a file included in http section):

    http {
        # some directives ...
        server {
            # ...
        }
        server {
            # ...
        }
        # ...
    }
    

提交回复
热议问题