日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

nginx 配置简介

發布時間:2025/7/25 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 nginx 配置简介 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

location 匹配規則

語法規則

location [=|~|~*|^~] /uri/ { … }

模式含義
location = /uri= 表示精確匹配,只有完全匹配上才能生效
location ^~ /uri^~ 開頭對URL路徑進行前綴匹配,并且在正則之前。
location ~ \.(gif|jpg|png|js|css)$對URL路徑進行后綴匹配,并且在正則之前。
location ~ pattern開頭表示區分大小寫的正則匹配
location ~* pattern開頭表示不區分大小寫的正則匹配
location /uri不帶任何修飾符,也表示前綴匹配,但是在正則匹配之后
location /通用匹配,任何未匹配到其它location的請求都會匹配到,相當于switch中的default

前綴匹配時,Nginx 不對 url 做編碼,因此請求為 /static/20%/aa,可以被規則 ^~ /static/ /aa 匹配到(注意是空格)

多個 location 配置的情況下匹配順序為(參考資料而來,還未實際驗證,試試就知道了,不必拘泥,僅供參考):

  • 首先精確匹配 =
  • 其次前綴匹配 ^~
  • 其次是按文件中順序的正則匹配
  • 然后匹配不帶任何修飾的前綴匹配。
  • 最后是交給 / 通用匹配
  • 當有匹配成功時候,停止匹配,按當前匹配規則處理請求

注意:前綴匹配,如果有包含關系時,按最大匹配原則進行匹配。比如在前綴匹配:location /dir01 與 location /dir01/dir02,如有請求 http://localhost/dir01/dir02/file 將最終匹配到 location /dir01/dir02

例子,有如下匹配規則:

location = / {echo "規則A"; } location = /login {echo "規則B"; } location ^~ /static/ {echo "規則C"; } location ^~ /static/files {echo "規則X"; } location ~ \.(gif|jpg|png|js|css)$ {echo "規則D"; } location ~* \.png$ {echo "規則E"; } location /img {echo "規則Y"; } location / {echo "規則F"; }復制代碼

那么產生的效果如下:

  • 訪問根目錄 /,比如 http://localhost/ 將匹配 規則A
  • 訪問 http://localhost/login 將匹配 規則B,http://localhost/register 則匹配 規則F
  • 訪問 http://localhost/static/a.html 將匹配 規則C
  • 訪問 http://localhost/static/files/a.exe 將匹配 規則X,雖然 規則C也能匹配到,但因為最大匹配原則,最終選中了 規則X。你可以測試下,去掉規則 X ,則當前 URL 會匹配上 規則C。
  • 訪問 http://localhost/a.gif, http://localhost/b.jpg 將匹配 規則D和 規則 E ,但是 規則 D 順序優先,規則 E 不起作用,而 http://localhost/static/c.png 則優先匹配到 規則 C
  • 訪問 http://localhost/a.PNG 則匹配 規則 E ,而不會匹配 規則 D ,因為 規則 E 不區分大小寫。
  • 訪問 http://localhost/img/a.gif 會匹配上 規則D,雖然 規則Y 也可以匹配上,但是因為正則匹配優先,而忽略了 規則Y。
  • 訪問 http://localhost/img/a.tiff 會匹配上 規則Y。

訪問 http://localhost/category/id/1111 則最終匹配到規則 F ,因為以上規則都不匹配,這個時候應該是 Nginx 轉發請求給后端應用服務器,比如 FastCGI(php),tomcat(jsp),Nginx 作為反向代理服務器存在。

所以實際使用中,筆者覺得至少有三個匹配規則定義,如下:

# 直接匹配網站根,通過域名訪問網站首頁比較頻繁,使用這個會加速處理,官網如是說。 # 這里是直接轉發給后端應用服務器了,也可以是一個靜態首頁 # 第一個必選規則 location = / {proxy_pass http://tomcat:8080/index }# 第二個必選規則是處理靜態文件請求,這是 nginx 作為 http 服務器的強項 # 有兩種配置模式,目錄匹配或后綴匹配,任選其一或搭配使用 location ^~ /static/ {root /webroot/static/; } location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {root /webroot/res/; }# 第三個規則就是通用規則,用來轉發動態請求到后端應用服務器 # 非靜態文件請求就默認是動態請求,自己根據實際把握 # 畢竟目前的一些框架的流行,帶.php、.jsp后綴的情況很少了 location / {proxy_pass http://tomcat:8080/ }復制代碼

rewrite 語法

  • last – 基本上都用這個 Flag
  • break – 中止 Rewirte,不再繼續匹配
  • redirect – 返回臨時重定向的 HTTP 狀態 302
  • permanent – 返回永久重定向的 HTTP 狀態 301

1、下面是可以用來判斷的表達式:

-f 和 !-f 用來判斷是否存在文件 -d 和 !-d 用來判斷是否存在目錄 -e 和 !-e 用來判斷是否存在文件或目錄 -x 和 !-x 用來判斷文件是否可執行復制代碼

2、下面是可以用作判斷的全局變量

例:http://localhost:88/test1/test2/test.php?k=v $host:localhost $server_port:88 $request_uri:/test1/test2/test.php?k=v $document_uri:/test1/test2/test.php $document_root:D:\nginx/html $request_filename:D:\nginx/html/test1/test2/test.php復制代碼

redirect 語法

server {listen 80;server_name start.igrow.cn;index index.html index.php;root html;if ($http_host !~ "^star\.igrow\.cn$") {rewrite ^(.*) http://star.igrow.cn$1 redirect;} }復制代碼

防盜鏈

location ~* \.(gif|jpg|swf)$ {valid_referers none blocked start.igrow.cn sta.igrow.cn;if ($invalid_referer) {rewrite ^/ http://$host/logo.png;} }復制代碼

根據文件類型設置過期時間

location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {if (-f $request_filename) {expires 1h;break;} }復制代碼

禁止訪問某個目錄

location ~* \.(txt|doc)${root /data/www/wwwroot/linuxtone/test;deny all; }復制代碼

一些可用的全局變量,可以參考獲取 Nginx 內置綁定變量章節。

nginx 內置綁定變量

部分常用變量如下:

名稱說明
$arg_name請求中的name參數
$args請求中的參數
$binary_remote_addr遠程地址的二進制表示
$body_bytes_sent已發送的消息體字節數
$content_lengthHTTP請求信息里的"Content-Length"
$content_type請求信息里的"Content-Type"
$document_root針對當前請求的根路徑設置值
$document_uri與$uri相同; 比如 /test2/test.php
$host請求信息中的"Host",如果請求中沒有Host行,則等于設置的服務器名
$hostname機器名使用 gethostname系統調用的值
$http_cookiecookie 信息
$http_referer引用地址
$http_user_agent客戶端代理信息
$http_via最后一個訪問服務器的Ip地址。
$http_x_forwarded_for相當于網絡訪問路徑
$is_args如果請求行帶有參數,返回“?”,否則返回空字符串
$limit_rate對連接速率的限制
$nginx_version當前運行的nginx版本號
$pidworker進程的PID
$query_string與$args相同
$realpath_root按root指令或alias指令算出的當前請求的絕對路徑。其中的符號鏈接都會解析成真是文件路徑
$remote_addr客戶端IP地址
$remote_port客戶端端口號
$remote_user客戶端用戶名,認證用
$request用戶請求
$request_body這個變量(0.7.58+)包含請求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比較有意義
$request_body_file客戶端請求主體信息的臨時文件名
$request_completion如果請求成功,設為"OK";如果請求未完成或者不是一系列請求中最后一部分則設為空
$request_filename當前請求的文件路徑名,比如/opt/nginx/www/test.php
$request_method請求的方法,比如"GET"、"POST"等
$request_uri請求的URI,帶參數
$scheme所用的協議,比如http或者是https
$server_addr服務器地址,如果沒有用listen指明服務器地址,使用這個變量將發起一次系統調用以取得地址(造成資源浪費)
$server_name請求到達的服務器名
$server_port請求到達的服務器端口號
$server_protocol請求的協議版本,"HTTP/1.0"或"HTTP/1.1"
$uri請求的URI,可能和最初的值有不同,比如經過重定向之類的

nginx.conf 配置詳解

#定義Nginx運行的用戶和用戶組 user www www;#nginx進程數,建議設置為等于CPU總核心數。 worker_processes 8;#全局錯誤日志定義類型,[ debug | info | notice | warn | error | crit ] error_log /var/log/nginx/error.log info;#進程文件 pid /var/run/nginx.pid;#一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(系統的值ulimit -n)與nginx進程數相除,但是nginx分配請求并不均勻,所以建議與ulimit -n的值保持一致。 worker_rlimit_nofile 65535;#工作模式與連接數上限 events {#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。use epoll;#單個進程最大連接數(最大連接數=連接數*進程數)worker_connections 65535; }#設定http服務器 http {include mime.types; #文件擴展名與文件類型映射表include /etc/nginx/sites-enabled/*; # 增加server配置文件夾default_type application/octet-stream; #默認文件類型#charset utf-8; #默認編碼server_names_hash_bucket_size 128; #服務器名字的hash表大小client_header_buffer_size 32k; #上傳文件大小限制large_client_header_buffers 4 64k; #設定請求緩client_max_body_size 8m; #設定請求緩#開啟高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對于普通應用設為 on,#如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。sendfile on; #開啟目錄列表訪問,合適下載服務器,默認關閉。autoindex on; tcp_nopush on; #防止網絡阻塞tcp_nodelay on; #防止網絡阻塞keepalive_timeout 120; #長連接超時時間,單位是秒#FastCGI相關參數是為了改善網站的性能:減少資源占用,提高訪問速度。下面參數看字面意思都能理解。fastcgi_connect_timeout 300;fastcgi_send_timeout 300;fastcgi_read_timeout 300;fastcgi_buffer_size 64k;fastcgi_buffers 4 64k;fastcgi_busy_buffers_size 128k;fastcgi_temp_file_write_size 128k;#gzip模塊設置gzip on; #開啟gzip壓縮輸出gzip_min_length 1k; #最小壓縮文件大小gzip_buffers 4 16k; #壓縮緩沖區gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)gzip_comp_level 2; #壓縮等級gzip_types text/plain application/x-javascript text/css application/xml; #壓縮類型,默認就已經包含text/html,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。gzip_vary on;#limit_zone crawler $binary_remote_addr 10m; #開啟限制IP連接數的時候需要使用upstream blog.ha97.com {#upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的幾率越大。server 192.168.80.121:80 weight=3; server 192.168.80.122:80 weight=2;server 192.168.80.123:80 weight=3;}#虛擬主機的配置server {#監聽端口listen 80; #域名可以有多個,用空格隔開server_name www.ha97.com ha97.com;index index.html index.htm index.php;root /data/www/ha97;location ~ .*\.(php|php5)?$ {fastcgi_pass 127.0.0.1:9000;fastcgi_index index.php;include fastcgi.conf; }#圖片緩存時間設置location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {expires 10d;}#JS和CSS緩存時間設置 location ~ .*\.(js|css)?$ {expires 1h;}#日志格式設定log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" $http_x_forwarded_for';#定義本虛擬主機的訪問日志access_log /var/log/nginx/ha97access.log access;#對 "/" 啟用反向代理location / {proxy_pass http://127.0.0.1:88;proxy_redirect off;proxy_set_header X-Real-IP $remote_addr;#后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IPproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#以下是一些反向代理的配置,可選。proxy_set_header Host $host;client_max_body_size 10m; #允許客戶端請求的最大單文件字節數client_body_buffer_size 128k; #緩沖區代理緩沖用戶端請求的最大字節數,proxy_connect_timeout 90; #nginx跟后端服務器連接超時時間(代理連接超時)proxy_send_timeout 90; #后端服務器數據回傳時間(代理發送超時)proxy_read_timeout 90; #連接成功后,后端服務器響應時間(代理接收超時)proxy_buffer_size 4k; #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小proxy_buffers 4 32k; #proxy_buffers緩沖區,網頁平均在32k以下的設置proxy_busy_buffers_size 64k; #高負荷下緩沖大小(proxy_buffers*2)proxy_temp_file_write_size 64k;#設定緩存文件夾大小,大于這個值,將從upstream服務器傳}#設定查看Nginx狀態的地址location /NginxStatus {stub_status on;access_log on;auth_basic "NginxStatus";auth_basic_user_file conf/htpasswd;#htpasswd文件的內容可以用apache提供的htpasswd工具來產生。}#本地動靜分離反向代理配置#所有jsp的頁面均交由tomcat或resin處理location ~ .(jsp|jspx|do)?$ {proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_pass http://127.0.0.1:8080;}#所有靜態文件由nginx直接讀取不經過tomcat或resinlocation ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ { expires 15d; }location ~ .*.(js|css)?$ { expires 1h; } } } 復制代碼

示例

nginx.conf

worker_processes 2; events {worker_connections 1024; }http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;include /etc/nginx/sites-enabled/*; } 復制代碼

/etc/nginx/sites-available/hostname

# 負載均衡 upstream balance {ip_hash;server <server1>:<port>;server <server2>:<port> down;server <server3>:<port> max_fails=3 fail_timeout=20s;server <server4>:<port>; }server {listen 80;server_name hostname;# redirect all http to httpsreturn 301 https://$host$request_uri; }server {listen 443 ssl;server_name hostname;ssl_certificate /etc/letsencrypt/live/hostname/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/hostname/privkey.pem;# disable SSLv2ssl_protocols TLSv1 TLSv1.1 TLSv1.2;# ciphers' order mattersssl_ciphers "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!aNULL";# the Elliptic curve key used for the ECDHE cipher.ssl_ecdh_curve secp384r1;# use command line# openssl dhparam -out dhparam.pem 2048# to generate Diffie Hellman Ephemeral Parametersssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;# let the server choose the cipherssl_prefer_server_ciphers on;# turn on the OCSP Stapling and verifyssl_stapling on;ssl_stapling_verify on;# http compression method is not secure in https# opens you up to vulnerabilities like BREACH, CRIMEgzip off;location /<request_uri> {proxy_pass http://balance;}# letencrypt httplocation ^~ /.well-known/acme-challenge/ {default_type "text/plain";root /mnt/var/www/<your name>/hostname;}# ip訪問限制location ~ /service/resources/JsApiTicket|AccessToken {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;proxy_pass http://127.0.0.1:<port>;proxy_set_header X-Forwarded-Proto $scheme;allow <ip1>;allow <ip2>;allow <ip3>;allow <ip4>;allow <ip5>; deny all;}location ~ /<request_uri> {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;proxy_pass http://127.0.0.1:<port>;proxy_set_header X-Forwarded-Proto $scheme;}location ~ /<request_uri> {include uwsgi_params;# 二者選其一即可 # uwsgi_pass unix://var/www/whb/webhook/uwsgi/uwsgi.sock;uwsgi_pass 127.0.0.1:<port>;}location ~ /url1/(.*)? {proxy_set_header Host <another hostname>;proxy_pass http://<remote_addr>:<port>/$1$is_args$args;proxy_set_header X-Real-IP $remote_addr;}location ~ /url2/(.*)? {proxy_set_header Host <another hostname>;proxy_pass https://<remote_addr>/$1$is_args$args; # 默認443端口proxy_set_header X-Real-IP $remote_addr;}location ~ /url2/(.*)? {proxy_set_header Host <another hostname>;proxy_pass http://<remote_addr>/$1$is_args$args; # 默認80端口proxy_set_header X-Real-IP $remote_addr;}#處理靜態文件請求location ^~ /static/ {root /webroot/static/;}location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {root /webroot/res/;}access_log /mnt/log/nginx/hostname/access.log;error_log /mnt/log/nginx/hostname/error.log; } 復制代碼

轉載于:https://juejin.im/post/5ad96864f265da0b8f62188f

總結

以上是生活随笔為你收集整理的nginx 配置简介的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。