为了安全,web服务需要使用ssl协议。跟常规80端口比起来,需要多执行如下两步:
对于初创公司,未必每个web应用都申请证书,所以我们要自己生成证书,这样小范围使用的时候,第一次打开网页的时候会有提示,点击继续浏览即可。若是用户量非常大,还是建议使用官方的证书。
生成证书的命令:
401 mkdir sslbak
402 cd sslbak/
403 openssl genrsa -out private_key.pem 2048
404 openssl req -new -key private_key.pem -out certificate_request.csr
405 ls
406 openssl x509 -req -days 3650 -in certificate_request.csr -signkey private_key.pem -out certificate.pem
将nginx的配置文件ai4green.conf里面listen 443 ssl; 这句的注释去掉,就行了。
当然在实践中,若碰到问题,还需要其它语句做出相应的修改和调整。
412 sudo vi ai4green.conf
413 sudo service nginx restart
server {
listen 80;
listen 443 ssl;
}
历经劫难后,ai4green.conf最终的配置信息为:
upstream ai4green{
ip_hash;
server 127.0.0.1:8080;
# server 127.0.0.1:8081;
}
server {
listen 80;
listen 443 ssl;
ssl_certificate /home/eln/sslbak/certificate.pem;
ssl_certificate_key /home/eln/sslbak/private_key.pem;
# end of optional ssl configuration
server_name huanju.airoot.org;
access_log /var/log/nginx/access.log;
# add for ssl error
if ($scheme = http) {
return 301 https://$host$uri?$args;
}
location / {
proxy_set_header Host $http_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;
# proxy_set_header X-Forwarded-Proto $scheme;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Host $host:$server_port;
# proxy_set_header X-Forwarded-Port $server_port;
# proxy_set_header Host $host:$server_port;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 60s;
proxy_send_timeout 90s;
proxy_read_timeout 90s;
proxy_buffering off;
proxy_temp_file_write_size 64k;
proxy_pass http://ai4green;
proxy_redirect off;
}
}
?现在再打开页面,果然是https开头了,搞定!
看网上有说加上这一段:
if ($scheme = http) {
return 301 https://$host$uri?$args;
}
能转发了,但是进入二级页面后直接nginx? 500还是502报错
出错原因之一是因为中间修改了语句:proxy_pass http://ai4green ,修改成proxy_pass https://ai4green了。后来改回proxy_pass http://ai4green
最终发现问题,原来以前为了能转发到特定的端口,转发规则上带了端口信息,参考这篇文档 uWSGI + nginx + systemd — The Pyramid Community Cookbook v0.2修改一下:
# 原配置
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header Host $host:$server_port;
# 现配置
proxy_set_header Host $http_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;