Nginx 的其中一個(gè)用途是做 HTTP 反向代理,下面簡單介紹 Nginx 作為反向代理服務(wù)器的方法。
場景描述:
- 訪問服務(wù)器上的README.md文件, http://192.168.6.6/readme.md, 服務(wù)器進(jìn)行反向代理,從https://github.com/yidao620c/scrapy-cookbook/blob/master/README.md獲取頁面內(nèi)容。
- 訪問服務(wù)的8080端口,服務(wù)器進(jìn)行反向代理, 跳轉(zhuǎn)到https://163.com
1. 配置https
1. 安裝openssl相關(guān)軟件
[root@lotus nginx]¥ yum -y install openssl*
2. 頒發(fā)證書給自己
[root@lotus nginx]$ openssl genrsa -des3 -out server.key 1024 # 用于生成rsa私鑰文件
[root@lotus nginx]$ openssl req -new -key server.key -out server.csr # openssl req 用于生成證書請求
[root@lotus nginx]$ openssl rsa -in server.key -out server_nopwd.key #利用openssl進(jìn)行RSA為公鑰加密
[root@lotus nginx]$ openssl x509 -req -days 365 -in server.csr -signkey server_nopwd.key -out server.crt
[root@lotus nginx]$ mv server.crt server_nopwd.key /usr/local/nginx/conf/
2. 在 conf.d目錄下新建 reve.conf文件
# 添加上面的https
server {
listen 443 ssl;
ssl_certificate server.crt;
ssl_certificate_key server_nopwd.key;
}
server {
listen 8080;
# 訪問8080端口,跳轉(zhuǎn)到網(wǎng)易首頁
location / {
proxy_pass https://163.com;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 訪問 8080:/readme.md 從github上獲取相應(yīng)的文件
location /readme.md {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass https://github.com/yidao620c/scrapy-cookbook/blob/master/README.md;
}
}
3. 重新啟動(dòng)nginx
[root@lotus nginx]$ ./sbin/nginx -s reload