在 Ubuntu 上使用 Nginx 设置 SSL 重定向,通常是指将所有 HTTP 请求自动重定向到 HTTPS。以下是详细的步骤指南:
首先,确保你已经安装了 Nginx。如果还没有安装,可以使用以下命令进行安装:
sudo apt update
sudo apt install nginx
你可以从多个证书颁发机构(CA)获取免费的 SSL 证书,例如 Let’s Encrypt。以下以 Let’s Encrypt 为例,使用 Certbot 自动获取和配置证书。
sudo apt install certbot python3-certbot-nginx
运行以下命令以获取证书,并自动配置 Nginx:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
将 yourdomain.com 和 www.yourdomain.com 替换为你的实际域名。Certbot 会自动检测 Nginx 配置文件的位置,并在需要时创建备份。
按照提示完成验证过程(通常是通过 HTTP-01 挑战),Certbot 会自动更新 Nginx 配置文件以启用 HTTPS。
如果已经手动配置了 SSL 或不想使用 Certbot,可以手动编辑 Nginx 配置文件来实现 HTTP 到 HTTPS 的重定向。
打开你的网站配置文件。通常位于 /etc/nginx/sites-available/ 目录下,例如 yourdomain.com.conf:
sudo nano /etc/nginx/sites-available/yourdomain.com.conf
确保你有一个 HTTP 服务器块(通常是默认的 000-default.conf),并添加重定向规则。例如:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location / {
return 301 https://$host$request_uri;
}
}
确保你有一个 HTTPS 服务器块,并正确配置 SSL 证书和密钥。例如:
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# 其他配置项,如根目录、索引文件等
root /var/www/yourdomain.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 可选:配置压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
在重新加载 Nginx 之前,建议先测试配置文件是否有语法错误:
sudo nginx -t
如果输出显示配置文件语法正确,继续下一步。
应用新的配置:
sudo systemctl reload nginx
如果你使用的是 UFW(Uncomplicated Firewall),确保允许 443 端口的流量:
sudo ufw allow 'Nginx Full'
或者手动允许 443 端口:
sudo ufw allow 443/tcp
打开浏览器,访问 http://yourdomain.com,应该会自动跳转到 https://yourdomain.com。
为了增强安全性,可以在 Nginx 配置中启用 HSTS,强制浏览器始终通过 HTTPS 访问你的网站。
在 HTTPS 服务器块中添加以下头部:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
完整的 HTTPS 服务器块示例:
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
root /var/www/yourdomain.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
注意:HSTS 一旦启用,浏览器将强制在指定时间内(例如一年)通过 HTTPS 访问该域名,无法通过 HTTP 访问。因此,在启用 HSTS 之前,请确保所有资源都通过 HTTPS 提供。
通过以上步骤,你可以在 Ubuntu 上使用 Nginx 设置 SSL 重定向,将所有 HTTP 请求自动转发到 HTTPS,从而提高网站的安全性。如果你有任何问题或需要进一步的帮助,请随时提问!