nginx實現請求轉發

反向代理適用于很多場合,負載均衡是最普遍的用法。

nginx?作為目前最流行的web服務器之一,可以很方便地實現反向代理。

nginx?反向代理官方文檔:?NGINX REVERSE PROXY

當在一臺主機上部署了多個不同的web服務器,并且需要能在80端口同時訪問這些web服務器時,可以使用?nginx?的反向代理功能: 用?nginx?在80端口監聽所有請求,并依據轉發規則(比較常見的是以 URI 來轉發)轉發到對應的web服務器上。

例如有?webmail?,?webcom?以及?webdefault?三個服務器分別運行在?portmail?,?portcom?,?portdefault?端口,要實現從80端口同時訪問這三個web服務器,則可以在80端口運行?nginx, 然后將?/mail?下的請求轉發到?webmail?服務器, 將?/com下的請求轉發到?webcom?服務器, 將其他所有請求轉發到?webdefault?服務器。

假設服務器域名為example.com,則對應的?nginx?http配置如下:

  1. ?
    http {
  2. ?
    server {
  3. ?
    server_name example.com;
  4. ?
    ?
  5. ?
    location /mail/ {
  6. ?
    proxy_pass http://example.com:protmail/;
  7. ?
    }
  8. ?
    ?
  9. ?
    location /com/ {
  10. ?
    proxy_pass http://example.com:portcom/main/;
  11. ?
    }
  12. ?
    ?
  13. ?
    location / {
  14. ?
    proxy_pass http://example.com:portdefault;
  15. ?
    }
  16. ?
    }
  17. ?
    }

以上的配置會按以下規則轉發請求(?GET?和?POST?請求都會轉發):

  • 將?http://example.com/mail/?下的請求轉發到?http://example.com:portmail/
  • 將?http://example.com/com/?下的請求轉發到?http://example.com:portcom/main/
  • 將其它所有請求轉發到?http://example.com:portdefault/

需要注意的是,在以上的配置中,webdefault?的代理服務器設置是沒有指定URI的,而?webmail?和?webcom?的代理服務器設置是指定了URI的(分別為?/?和?/main/)。 如果代理服務器地址中是帶有URI的,此URI會替換掉?location?所匹配的URI部分。 而如果代理服務器地址中是不帶有URI的,則會用完整的請求URL來轉發到代理服務器。

官方文檔描述:

If the URI is specified along with the address, it replaces the part of the request URI that matches the location parameter. If the address is specified without a URI, or it is not possible to determine the part of URI to be replaced, the full request URI is passed (possibly, modified).

以上配置的轉發示例:

  • http://example.com/mail/index.html?->?http://example.com:portmail/index.html
  • http://example.com/com/index.html?->?http://example.com:portcom/main/index.html
  • http://example.com/mail/static/a.jpg?->?http://example.com:portmail/static/a.jpg
  • http://example.com/com/static/b.css?->?http://example.com:portcom/main/static/b.css
  • http://example.com/other/index.htm?->?http://example.com:portdefault/other/index.htm

本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/102471

(34)
單爆手單爆手
上一篇 2018-07-08 19:32
下一篇 2018-07-08 21:14

相關推薦

  • yum運用

    隨便寫寫,大佬勿噴

    Linux筆記 2018-04-20
  • Linux系統報錯修復的方法 . 2

    /boot/vmlinuz-2.6.32-696.el6.x86_64.img文件丟失怎么辦
    內有centos6的啟動流程

    2018-05-12
  • ansible的使用

    運維自動化發展歷程及技術應用 IAAS基礎設置即服務,提供硬件服務 PAAS平臺即服務,提供操作系統服務 SAAS軟件即服務,提供整套服務   ansible的安裝 yum -y install ansible ansible –version 查看版本信息   /etc/ansible/ansible.cfg? 配置文件 /…

    2018-06-04
  • 帶你認識Linux中的通配符

    所謂的通配是指:顯示以指定條件的文件,英文名為glob。通配符是一種特殊語句,用來模糊搜索文件。當查找文件夾時,可以使用它來代替一個或多個真正字符它使得文件管理更加快速,便捷,大大提升了工作效率。

    2018-04-01
  • PXE自動化安裝系統相關實驗

    PXE(Preboot Execution Environment):預啟動執行環境,PXE是由Intel設計的協議,它可以使計算機通過網絡而不是從本地硬盤、光驅等設備啟動。本節將帶你學習dhcp,tftp服務器的搭建,以及使用PXE安裝系統

    2018-05-26
欧美性久久久久