Nginx配置——單域名反向代理多個端口

今天給新買的云服務器安裝Nginx,用于部署自己的測試項目和博客,之前域名一直只綁定了一個端口用來跑博客項目,現(xiàn)在希望把后臺接口也通過域名方式來訪問,為此開始了一次Nginx的配置之旅。

一、安裝Nginx

安裝Nginx相對來說是非常簡單的,運行下面兩條命令即可。

sudo yum install epel-release
sudo yum install nginx

安裝成功后,設置開機啟動。

sudo systemctl enable nginx 

啟動nginx,訪問80端口,發(fā)現(xiàn)已經(jīng)啟動成功了。

sudo systemcyl start nginx

二、配置Nginx

2.1 nginx.conf

接下來,我們進入nginx目錄下,找到nginx.conf文件開始配置;這里我把nginx.conf文件中的server配置統(tǒng)統(tǒng)刪除了,以后我們再配置新的server,只需要再conf.d文件夾中創(chuàng)建新的*.conf即可。

cd /etc/nginx
vim nginx.conf

配置如下:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$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/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;   # 統(tǒng)一管理新增server配置等

}

2.2 main.conf

接下來,我們需要配置一個server用于端口服務的反向代理,進入conf.d文件夾新建一個main.conf。

cd /etc/nginx/conf.d
touch main.conf

配置main.conf如下:

server {
  listen    80 default_server;
  listen    [::]:80 default_server;
  server_name   jotyy.top;

  location / {
    proxy_pass  http://127.0.0.1:8999;  #端口1:用于博客主站訪問
    proxy_read_timeout  300;
    proxy_connect_timeout   300;
    proxy_redirect  off;

    proxy_set_header    X-Forwarded-Proto $scheme;
    proxy_set_header    Host          $http_host;
    proxy_set_header    X-Real-IP     $remote_addr;
  }

  location /api/ {
    proxy_pass  http://127.0.0.1:8666/; #端口2:用于接口訪問,這里一定要帶上末尾的'/'
    proxy_read_timeout  300;
    proxy_connect_timeout   300;
    proxy_redirect  off;

    proxy_set_header    X-Forwarded-Proto $scheme;
    proxy_set_header    Host          $http_host;
    proxy_set_header    X-Real-IP     $remote_addr;
  }
  
  error_page 500 502 503 504 /50x.html; 
  location = /50x.html {
    root /usr/share/nginx/html;
  }
}

接下來,我們通過http://jotyy.top/api/就可以訪問到接口啦。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容