如果我有重定向服务器和主服务器,我应该如何在 nginx 中命名我的服务器?

如果我有重定向服务器和主服务器,我应该如何在 nginx 中命名我的服务器?

假设我的主服务器用于提供服务https://www.example.com,而重定向服务器用于重定向http://www.example.comhttps://www.example.com。我应该如何命名这两个服务器?是否有最佳实践?

服务器名称是否主要是个人偏好,以至于我可以命名任何名称?

答案1

它们都应该命名为www.example.com。这个名称通常实际上非常重要,因为如果您在同一个 IP 地址上托管多个虚拟主机,nginx将使用名称将应处理请求的虚拟主机与Hosthttp 请求标头中的虚拟主机进行匹配。如果您有两个虚拟主机但协议不同(http/https),则将使用协议(或端口Listen)进一步区分两个虚拟主机。

答案2

服务器名称是 nginx 配置的重要组成部分。如果您从具有单个公共 IP 的服务器为多个域/子域提供服务,则该server_name指令会告诉 nginx 哪个服务器应该响应请求。如果没有匹配的服务器名称,nginx 接下来会查找默认服务器(如果存在),该服务器充当某种“全部捕获”服务器。

这是一个配置示例对于 http -> https 重定向,您还可以看到如何正确命名服务器而不会出现错误。

/etc/nginx/sites-available/www.example.com.vhost

# This server will redirect all http -> https
server {
        # Listen for both IPv4 and IPv6 requests.
        listen 80;
        listen [::]:80;
        server_name www.example.com example.com;

        # This section assuming you're using Let's Encrypt / certbot
        location ^~ /.well-known/acme-challenge/ {
            default_type "text/plain";
            root         /path/to/your/document/root
        }
        location = /.well-known/acme-challenge/ {
            return 404;
        }

        # Here's where your 301 permanent redirect to the https:/www version happens.
        return 301 https://www.example.com$request_uri;

}

# This server will redirect all https requests without www to the version with www
server {
        # Listen for both IPv4 and IPv6 requests and activate http2.
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name example.com;

        ssl on;
        # Paths to certificates assuming you're using Let's Encrypt / certbot
        ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
        # There's much more directives you should fine tune for https, but that's another task.

        # Here's where your 301 permanent redirect to the https://www version happens.
        return 301 https://www.example.com$request_uri;
}

# This server will actually server your https content.
server {
        # Listen for both IPv4 and IPv6 requests and activate http2.
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name www.example.com;

        ssl on;
        # Paths to certificates assuming you're using let's encrypt / certbot
        ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
        # There's much more directives you should fine tune for https, but that's another task.

        ####
        #
        # Your server directives go here.
        #
        ####
}

相关内容