当前位置: 代码网 > 服务器>网络>https > Nginx设置https和http同时使用同一个端口访问

Nginx设置https和http同时使用同一个端口访问

2025年05月30日 https 我要评论
以下是一个同时使用 http 和 https 并通过 8070 端口的配置示例:server { listen 8070; server_name your_domain.com;

以下是一个同时使用 http 和 https 并通过 8070 端口的配置示例:

server {
    listen 8070;
    server_name your_domain.com;

    location / {
        root /var/www/html;
        index index.html;
    }
}

server {
    listen 8070 ssl;
    server_name your_domain.com;

    # ssl 证书和私钥的路径
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;

    # 可选:设置 ssl 协议和加密套件
    ssl_protocols tlsv1.2 tlsv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ecdhe-rsa-aes256-gcm-sha512:dhe-rsa-aes256-gcm-sha512:ecdhe-rsa-aes256-gcm-sha384:dhe-rsa-aes256-gcm-sha384:ecdhe-rsa-aes256-sha384;

    # 可选:设置 hsts 头,让浏览器强制使用 https
    add_header strict-transport-security "max-age=31536000; includesubdomains; preload";

    location / {
        root /var/www/html;
        index index.html;
    }
}

在上述配置中:

第一个 server 块:

  • listen 8070;:让 nginx 监听 8070 端口进行 http 访问。
  • server_name your_domain.com;:指定服务器的域名,将 your_domain.com 替换为你的实际域名。
  • location /:将请求发送到 /var/www/html 目录下的静态文件,你可以根据需要修改,如将请求代理到其他服务器。

第二个 server 块:

  • listen 8070 ssl;:让 nginx 监听 8070 端口进行 https 访问。
  • ssl_certificate 和 ssl_certificate_key:指定 ssl 证书和私钥的路径。
  • ssl_protocols 和 ssl_ciphers:配置 ssl 协议和加密套件,提高安全性。
  • add_header strict-transport-security:启用 hsts,让浏览器强制使用 https。
  • location /:与 http 部分类似,将请求发送到 /var/www/html 目录下的静态文件,你可以根据需要修改。

注意事项

虽然可以在同一端口同时提供 http 和 https 服务,但这种配置可能会引起混淆,并且不是一个推荐的最佳实践。通常建议将 http 服务和 https 服务分别部署在不同的端口,例如 80 端口用于 http,443 端口用于 https,然后使用重定向将 http 请求重定向到 https 以确保安全。以下是一个将 80 端口的 http 请求重定向到 443 端口的 https 的示例:

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

到此这篇关于nginx设置https和http同时使用同一个端口访问的文章就介绍到这了,更多相关nginx 同时使用同一个端口访问内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网! 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com