插件窝 干货文章 Nginx部署https网站并配置地址重写的方法

Nginx部署https网站并配置地址重写的方法

Nginx 重写 SSL yourdomain 930    来源:    2025-04-21

Nginx部署HTTPS网站并配置地址重写指南

一、HTTPS基础配置

1. 获取SSL证书

首先需要获取SSL证书,可以选择: - 从Let's Encrypt获取免费证书 - 从商业CA购买证书 - 使用自签名证书(仅测试环境)

2. 安装证书

将获取的证书文件(通常包括.crt和.key文件)上传到服务器,例如:

/etc/ssl/certs/your_domain.crt
/etc/ssl/private/your_domain.key

3. 基本HTTPS配置

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /etc/ssl/certs/your_domain.crt;
    ssl_certificate_key /etc/ssl/private/your_domain.key;

    # 推荐的安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;

    # 其他配置...
    root /var/www/yourdomain.com;
    index index.html index.htm;
}

二、HTTP重定向到HTTPS

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

三、常用URL重写配置

1. 基本重定向

# 重定向旧URL到新URL
location /old-page {
    return 301 https://$host/new-page;
}

2. 移除www前缀

server {
    listen 443 ssl;
    server_name www.yourdomain.com;
    return 301 https://yourdomain.com$request_uri;
}

3. 添加www前缀

server {
    listen 443 ssl;
    server_name yourdomain.com;
    return 301 https://www.yourdomain.com$request_uri;
}

4. 隐藏index.php(适用于PHP应用)

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

5. 强制尾部斜杠

rewrite ^([^.]*[^/])$ $1/ permanent;

6. 移除尾部斜杠

rewrite ^/(.*)/$ /$1 permanent;

四、高级重写示例

1. 条件重写

# 只有当请求来自特定IP时才重写
if ($remote_addr = 192.168.1.100) {
    rewrite ^/special-page$ /special-content break;
}

2. 基于User-Agent的重写

# 移动设备重定向到移动版
if ($http_user_agent ~* "(android|iphone|ipod)") {
    rewrite ^/$ /mobile break;
}

3. 查询参数重写

# 将?page=123重写为/page/123
if ($args ~* "^page=([0-9]+)") {
    set $page $1;
    rewrite ^/$ /page/$page? permanent;
}

五、性能和安全优化

  1. 启用HTTP/2(在listen行添加http2):
listen 443 ssl http2;
  1. 启用OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /path/to/chain.pem;
  1. 安全头设置
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
add_header X-XSS-Protection "1; mode=block";

六、调试技巧

  1. 检查Nginx配置语法:
nginx -t
  1. 重新加载配置:
nginx -s reload
  1. 查看重写日志(在http块中添加):
rewrite_log on;
error_log /var/log/nginx/rewrite.log notice;

通过以上配置,您可以实现安全的HTTPS网站部署,并灵活地控制URL重写规则,满足各种业务需求。