1. 程式人生 > 實用技巧 >工作中nginx整理

工作中nginx整理

工作中nginx整理

 nginx很強大,匹配規則也很豐富。本人對nginx的用法也是一知半解,只能根據實際需求去學習並總結起來。以下是我工作中用到的nginx一些用法整理,前幾個還是比較常用的,最後一個就我也是第一次見。

一、配置404頁面(針對同一域名不同服務)   針對某個常用活動的域名abc.gdljy.cn,在這個域名下都使用同一個404頁面,大家配的多,類似這樣子。 /home/ljy/app/nginx/html/mddd_404 下面有一個index.html,然後這個index.html引用同級目錄images的一個圖片: <img src="images/404.jpg" width="100%">

如果針對某個活動,假設叫dg20200918

具體的location匹配某個活動,某個活動自己定義自己的404頁面
1 location ^~ /dg20200918 {
2     root /home/gdtc/app/nginx/html;
3     index index.html;
4     error_page 403 404 /dg404;
5     location ~ /dg404 {
6     root /home/gdtc/app/nginx/html;
7     }
8 }
View Code

二、nginx跳到指定redirect頁面

需求:專案啟動開發前,需要給運營同事一個海報地址,然後還要生成一個二維碼給他們;我一般那會直接用location匹配一個專案目錄,然後專案地址就這樣直接發這個給他們了:a.gdljy.cn/dcbg20201013/

location ^~ /dcbg20201013 {
    root /home/ljy/data;
}

然後專案啟動後(tomcat跑的),停服務就悲劇了,因為開發人員給的地址是一個專案下叫redirect.html 的頁面,不應該是a.gdljy.cn/dcbg20201013/,並且預設是找 index.html 的,找不到就404了。

那怎麼辦呢,dcbg20201013這個專案地址已經給出去了(海報不是說換就換的,真是一失足成千古恨,淚 = =! ),那麼就建一個臨時目錄唄,用rewrite去實現原目錄重寫到這個目錄下的redirect.html 問題解決:

弄一個臨時目錄為bg20201013 ,bg20201013變成真正的專案目錄,原來的目錄變成一個傀儡,僅僅充當一個被重寫的地址, tomcat的server.xml也得改,Context path由原來的dcbg20201013改成bg20201013。

 1         location ^~ /bg20201013 {
 2               proxy_pass http://14.18.102.235:8290;
 3               error_page 502 404 /dcbg-404;
 4               location ~ /dcbg-404 {
 5                    root  /home/gdtc/app/nginx/html;
 6               }
 7               ##ip受限頁面
 8               error_page 403 /dcbg-403;
 9               location ~ /dcbg-403 {
10                    root  /home/gdtc/app/nginx/html;
11               }
12          }
13 #這是原來給出去的二維碼地址
14         location ^~ /dcbg20201013 {
15            rewrite  ^/(.*)$  https://act.gdlottery.cn/bg20201013/redirect.html permanent;
16         }
View Code

三、nginx問題之如何將GET問題轉換為POST請求

開發調介面,需要從原來的https://a.gdljy.cn/dg20200918/notification,跳到:

https://a.gdljy.cn/gd20201214/notification,我原來用rewrite寫的,發現跟proxy_method一起用是無法生效的,幸好這個proxy_pass也能跳。

1 location ^~ /dg20200918/notification {
2     proxy_method POST;
3     proxy_pass     https://a.gdljy.cn/gd20201214/notification;
4    #rewrite  ^/(.*)$  https://a.gdljy.cn/gd20201214/notification permanent;    
5 }
View Code