配置nginx在同域名下的http/https有选择访问


生产环境中,遇到了这样一个需求,http://www.domain.com默认对所有用户开放,http://www.domain.com/login是用户登录网站的入口,大家都知道http是没有加密的,对于帐号这类的敏感信息一定要妥善处理,https出来就是解决这个问题的。具体的你可以参考豆瓣网站,用户POST提交的url是HTTPS的,你可以打开debug工具进行跟踪,这里就不多说这个问题了。

我现在处理的思路是这样的,https直接代理http(因为都在一个域中,访问效果都是一样的,不一样的就是端口而已(80、443)),为了简便阐述问题,我https做http的代理,我认为这个是我的最优解,起码我在网上还没有找到有关这方面的资料,好,我直接贴上nginx配置文件参考。

test.conf

#https proxy
server {
        listen       443 ssl;
        server_name  www.domain.com;

        ssl on;
        ssl_certificate /usr/local/nginx/conf/vhost/safekey/www.domain.crt;
        ssl_certificate_key /usr/local/nginx/conf/vhost/safekey/www.domain.key;

        location / {

			#参数需求  只代理http://www.domain.com/?g=admin&m=index&a=login&do=1进行HTTPS传输
			if ( $args !~ g=admin&m=index&a=login&do=1)
			{
				rewrite (.*) http://www.domain.com$1 permanent;
			}

			#uri需求 可以注释。 如果是http://www.domain.com/login 使用HTTPS传输
			if ( $request_uri !~ /login.*$)
			{
				rewrite (.*) http://www.domain.com$1 permanent;
			}

			#如果上面的条件没有满足 就全权代理http 即我们看到的https://www.domain.com
            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_pass http://www.domain.com;
        }
}

#普通http
server {
        listen       80;
        server_name  www.domain.com;
        root /home/vhost/domain;
		index  index.html index.htm index.php;

        access_log  logs/access.domain.log;
        error_log logs/error.domain.log;

        location / {
        }

        error_page   404 403 402 500 502 503 504  /404.html;
        location = /404.html {
        }

        location ~ \.php$ {
           fastcgi_pass   127.0.0.1:9000;
           try_files $uri =404;
           fastcgi_index  index.php;
           fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
           include        fastcgi_params;
        }
}

这个是我生产环境下版本,你可以参考,不求完美,只有实用,如果您有更好的建议,请与我联系。关于更多nginx方面的资料,请参阅这里。程序员没有什么会不会的,只有不肯学的。


发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论审核已启用。您的评论可能需要一段时间后才能被显示。