
假設我的主伺服器要提供服務https://www.example.com
,重定向伺服器要重定向http://www.example.com
到https://www.example.com
.我應該如何命名這兩個伺服器?有沒有一種最佳實踐?
伺服器名稱主要是個人喜好,以便我可以命名任何東西嗎?
答案1
他們都應該被命名www.example.com
。該名稱實際上通常非常重要,因為如果您在同一 IP 位址上託管多個虛擬主機,則將使用該名稱將應處理請求的虛擬主機與http 請求標頭nginx
中的虛擬主機相符。Host
在您有兩個虛擬主機但協定不同(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.
#
####
}