配置Ubuntu Nginx以使用SSL和HSTS(HTTP Strict Transport Security)可以增强网站的安全性。以下是详细的步骤:
如果你还没有安装Nginx,可以使用以下命令进行安装:
sudo apt update
sudo apt install nginx
你可以使用Let’s Encrypt免费获取SSL证书。首先,安装Certbot和Nginx插件:
sudo apt install certbot python3-certbot-nginx
然后,运行Certbot来获取并配置SSL证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示完成证书的获取和配置。
编辑Nginx配置文件以启用HSTS。通常,Nginx的主配置文件位于/etc/nginx/nginx.conf,但你可能需要编辑特定站点的配置文件,通常位于/etc/nginx/sites-available/yourdomain.com。
打开你的站点配置文件:
sudo nano /etc/nginx/sites-available/yourdomain.com
在server块中添加以下HSTS头信息:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
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/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
在保存并关闭文件后,测试Nginx配置是否正确:
sudo nginx -t
如果没有错误,重启Nginx以应用更改:
sudo systemctl restart nginx
你可以使用浏览器开发者工具或在线工具(如SSL Labs)来验证HSTS是否已正确配置。
通过以上步骤,你已经成功配置了Ubuntu Nginx以使用SSL和HSTS。这样可以确保你的网站在传输数据时使用HTTPS,并且浏览器会记住在未来的一年内始终使用HTTPS访问你的网站。