一、nginx if判斷無效
在使用nginx if語句時,有時候會發現if語句並沒有按照預期執行,因此,在編寫nginx規則時,請注意以下幾點,以保證if語句可以正常運行:
1、if語句只能在 server、location、if 和 limit_except 塊內使用。
2、if 後的條件必須用空格隔開。
3、if 後的條件不僅支持在 location 里設置,同時也支持在 server 塊里設置。
4、在 location 里的 if 後如需使用反向代理,就不能用 try_files 。
如下所示,是一個if語句條件判斷無效的例子:
server { listen 80; server_name example.com; if ($host = 'www.example.com') { return 301 $scheme://example.com$request_uri; } ... }
上述代碼中,$host變量應該是通過nginx自動獲取的,而它沒有用空格隔開if語句的條件,因此if語句無效。正確的寫法應該是:
server { listen 80; server_name example.com; if ($host = 'www.example.com') { return 301 $scheme://example.com$request_uri; } ... }
二、nginx iframe跨域
在前後端分離的項目中,為了保證安全性,通常會使用同源策略去限制頁面的操作,例如防止跨域訪問,但是有時候我們還是需要跨域訪問,這時就需要用到 iframe 了。
當 iframe 的src屬性的域名與父頁面的域名不一致時,會出現跨域問題,此時,我們就可以利用nginx來解決這個問題。下面是一個利用nginx解決iframe跨域問題的示例:
location = /cross-domain.html { add_header 'Access-Control-Allow-Origin' 'http://target-site.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Credentials' 'true'; alias /path/to/cross-domain.html; }
上述代碼中,另一個網站(target-site.com)想要在自己的網站上嵌入一個content-site.com的內容,此時需要訪問包含在 cross-domain.html 文件中的 iframe,並且這個iframe要在target-site.com網站中訪問,而訪問時需要添加 Access-Control-Allow-Headers 和 Access-Control-Allow-Origin 等頭信息,來實現某些getCredientials等操作。
三、nginx if判斷
nginx if語句不僅可以判斷變量,還可以根據自定義表達式進行判斷,下面是其語法:
if(表達式1) {...} // 表達式 可以使用正則表達式來匹配字符串 if(表達式2) {...} // 表達式2 可以使用變量名,判斷變量的值 if(表達式3) {...} // 表達式3 可以使用數字,判斷變量是否等於/小於/大於指定數字
可以用來進行 if 判斷的變量主要有:
1、$request_uri:請求uri
2、$host:請求的主機名
3、$http_x_forwarded_for:使用了proxy_pass代理後,客戶端的Ip地址會被添加到http請求頭的X-Forwarded-For字段中,使用$http_x_forwarded_for 來獲取這個字段的值。
下面是一個使用if語句進行判斷的示例:
location /path1 { if ( $host != 'www.example.com' ) { return 404; } proxy_pass http://backend2; }
上述代碼中,只有當請求的主機名為www.example.com時,才會反向代理到http://backend2 去。
四、小結
通過以上的文章內容可以看到,nginx if語句的使用與運用有很多優點,如可以進行簡單的判斷操作,以及可以解決一些跨域問題。但需要注意if語句只能在server、location、if 和 limit_except 塊內使用,並且if語句後的條件必須要用空格隔開。
代碼示例:
server { listen 80; server_name example.com; if ($host = 'www.example.com') { return 301 $scheme://example.com$request_uri; } location = /cross-domain.html { add_header 'Access-Control-Allow-Origin' 'http://target-site.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Credentials' 'true'; alias /path/to/cross-domain.html; } location /path1 { if ( $host != 'www.example.com' ) { return 404; } proxy_pass http://backend2; } }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/292784.html