插件窝 干货文章 Nginx下如何配置Frp强制重定向为https

Nginx下如何配置Frp强制重定向为https

Nginx 配置 server proxy 580    来源:    2025-04-22

Nginx 配置 Frp 强制 HTTPS 重定向

要在 Nginx 中配置 Frp 服务强制重定向到 HTTPS,你可以按照以下步骤操作:

方法一:使用 Nginx 的 301 重定向

  1. 编辑你的 Nginx 配置文件(通常在 /etc/nginx/conf.d//etc/nginx/sites-available/ 目录下)

  2. 添加以下配置:

server {
    listen 80;
    server_name your.domain.com;  # 替换为你的域名

    # 强制重定向到 HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name your.domain.com;

    # SSL 配置
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/key.pem;

    # 其他 SSL 相关配置...

    # Frp 代理配置
    location / {
        proxy_pass http://127.0.0.1:7500;  # 假设 frp 监听在 7500 端口
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

方法二:使用 Nginx 的 rewrite 规则

如果你需要更灵活的重定向规则,可以使用 rewrite:

server {
    listen 80;
    server_name your.domain.com;

    # 重定向所有 HTTP 请求到 HTTPS
    rewrite ^(.*)$ https://$host$1 permanent;
}

注意事项

  1. 确保你已经正确配置了 SSL 证书
  2. 检查 Frp 的配置文件中 vhost_http_portvhost_https_port 设置是否正确
  3. 如果你使用 Frp 的 HTTPS 功能,确保 Nginx 和 Frp 的 SSL 配置不冲突
  4. 修改配置后,记得测试并重新加载 Nginx: bash nginx -t systemctl reload nginx

完整的 Frp + Nginx HTTPS 配置示例

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

server {
    listen 443 ssl http2;
    server_name frp.example.com;

    ssl_certificate /etc/letsencrypt/live/frp.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/frp.example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    location / {
        proxy_pass http://127.0.0.1:7500;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    access_log /var/log/nginx/frp.access.log;
    error_log /var/log/nginx/frp.error.log;
}

这样配置后,所有通过 HTTP 访问的请求都会被自动重定向到 HTTPS。