之前已經在centos7上安裝好了nginx,目錄在 /etc/nginx/。
其中配置文件是 /etc/nginx/conf.d/default.conf ,
作為反向代理要添加一個路由到本機別的端口可以這樣:
server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; }
location ^~ /guacamole/ { proxy_pass http://127.0.0.1:4822; } #上面一段表示以 url 以 guacamole 開頭的都路由到本機4822端口去
#error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 }
至於什么時候用波浪線?
- ~,波浪線表示執行一個正則匹配,區分大小寫
- ~*,表示執行一個正則匹配,不區分大小寫
- ^~,表示普通字符匹配,如果該選項匹配,只匹配該選項,不匹配別的選項,一般用來匹配目錄
- =,進行普通字符精確匹配
- @,定義一個命名的 location,使用在內部定向時,例如 error_page, try_files
location 匹配的優先級(與location在配置文件中的順序無關)?
= 精確匹配會第一個被處理。如果發現精確匹配,nginx停止搜索其他匹配。
普通字符匹配,正則表達式規則和長的塊規則將被優先和查詢匹配,也就是說如果該項匹配還需去看有沒有正則表達式匹配和更長的匹配。
^~ 則只匹配該規則,nginx停止搜索其他匹配,否則nginx會繼續處理其他location指令。
最后匹配理帶有""和"*"的指令,如果找到相應的匹配,則nginx停止搜索其他匹配;當沒有正則表達式或者沒有正則表達式被匹配的情況下,那么匹配程度最高的逐字匹配指令會被使用。
嘗試理解以下:
location = / { # 只匹配"/". [ configuration A ] } location / { # 匹配任何請求,因為所有請求都是以"/"開始 # 但是更長字符匹配或者正則表達式匹配會優先匹配 [ configuration B ] } location ^~ /images/ { # 匹配任何以 /images/ 開始的請求,並停止匹配 其它location [ configuration C ] } location ~* .(gif|jpg|jpeg)$ { # 匹配以 gif, jpg, or jpeg結尾的請求. # 但是所有 /images/ 目錄的請求將由 [Configuration C]處理. [ configuration D ] }
僅以備忘,來自: Nginx location匹配規則 - 簡書 (jianshu.com)