Lnmp 一鍵安裝包 簡單反向代理設置
Nginx是一個高性能的HTTP和反向代理服務器,使用Nginx,只需要簡單的幾條命令保存到文件,即可實現簡單、基本反向代理功能。
這里以LNMP一鍵安裝包為例,首先請創建虛擬主機。創建虛擬主機請參考:
https://lnmp.org/faq/lnmp-vhost-add-howto.html
一、進入相關目錄
如創建一個網址為“www.test1.com”的虛擬主機
進入LNMP一鍵包的虛擬主機配置文件夾,執行:cd /usr/local/nginx/conf/vhost
找到剛剛創建的“www.test1.com.conf”文件,并編輯。
二、添加反向代理規則
1、方法一
server
{
listen 80;
server_name www.test1.com;
location / {
proxy_set_header $host www.test2.com;
proxy_pass http://www.test2.com/;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
以上代碼,表示使用“www.test1.com”反向代理“www.test2.com”,然后保存文件即可。
備注:用這種反向代理方法也可以解決國內ip被封80端口的問題。只需要給被反向代理的域名加上端口,例如上面的可以改成:http://www.test2.com:82/;
這樣當訪問www.test1.com時,就可以訪問www.test2.com:82的網站了。
注意:如果沒有上面紅色的那段代碼,會導致訪問www.test1.com靜態頁時正常,但訪問動態頁時,會跳轉到www.test2.com 。這點很重要。
2、方法二
上面的方法就可以實現反向代理,這里再提供一種代碼的寫法:
server {
listen 80;
server_name www.test1.com;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
access_log /home/www/logs/www.test1.com_access.log;
location /robots.txt {
root /home/www/www.test1.com;
}
location / {
proxy_pass http://www.test2.com;
}
}
三、測試
1、測試規則是否正確
/usr/local/nginx/sbin/nginx -t
若提示:“the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok configuration file /usr/local/nginx/conf/nginx.conf test is successful”表示正常,若有錯誤請根據錯誤提示排除問題。
2、重載nginx規則
service nginx reload
執行以上代碼即可生效。
新聞熱點
疑難解答