多個網域名稱共用一個ip與port | nginx反向代理設定 Nginx Reverse Proxy Configuration

Multiple Domain Names Sharing a Single IP and Port | Nginx Reverse Proxy Configuration

會有這樣的需求是因為本來的網站 bian0726.com 是架設在 mac 裡面的虛擬機

網卡設定為橋接模式,跟實體機在同樣的網域

外部進來的連線,透過路由器進行轉發到虛擬機


但後來又多了 wp.bian0726.com 這個網站

這個網站架設在實體機上,使用同樣的固定 ip 以及 80 port

發現在路由器裡面沒有辦法進行這樣的設定

不過因為實體機裡面的網站是用 nginx 架設的


想說 nginx 應該會有可以設定的方式

就在網路上找到了 nginx 反向代理這個做法

反向代理有很多不同的設定方式

可以依照自己的需求進行調整

下面紀錄我的作法


進路由後台把外部連線改為轉發到實體機

虛擬機中的設定不需要改動

更改實體機的 nginx config 設定檔

重新載入 nginx

 

測試連線後,可以正常連線

這樣就完成了多個網域名稱共用一個 ip 與 port 的需求了


English version

The need arises because the original website "bian0726.com" was set up on a virtual machine in a Mac.

The network card was set to bridge mode, putting it in the same network as the physical machine.

External connections were forwarded by the router to the virtual machine.

However, later on a new website "wp.bian0726.com" was added.

This new website is set up on the physical machine, using the same fixed IP and port 80.

It was found that such a configuration could not be set up in the router.

But since the website on the physical machine is set up using Nginx, I thought there might be a way to configure it with Nginx.

So, I searched online and found the Nginx reverse proxy method.

There are many different ways to configure a reverse proxy, which can be adjusted according to one's needs.

Here’s how I did it:

  1. Access the router backend and change the external connection to forward to the physical machine.
  2. No changes are needed for the virtual machine’s configuration.
  3. Modify the Nginx config file on the physical machine.
  4. Reload Nginx.

After testing the connection, it worked successful.

This completes the requirement for multiple domain names sharing a single IP and port.


Nginx 設定檔配置
Nginx configuration steps

server {
    listen 80;
    server_name bian0726.com; // Host Name (主機名稱)

    location / {
        proxy_redirect off;
        proxy_set_header Host $host; // Set the Host header (重新設定 Host)
        proxy_set_header X-Real-IP $remote_addr; // Set the real client IP (設置真實用戶端 IP)
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; // Add forwarded client IPs (添加轉發的用戶端 IP)
        proxy_pass http://192.168.0.198; // The IP address to redirect to (虛擬機的目標 IP)
    }
}

server {
    listen 80;
    server_name wp.bian0726.com; // Host Name (主機名稱)

    location / {
        root   /wordpress; // File location on the physical machine (實體機的檔案位置)
        index  index.html index.htm index.php; // Default files to load (預設載入檔案)
        try_files $uri $uri/ /index.php$args; // URL rewrite settings for WordPress (WordPress 的網址導向設定)
    }
}

#網域名稱共用ip#nginx反向代理

留言

這個網誌中的熱門文章

以成 - 個人網站

理膚寶水評價、心得 | 理膚寶水 La Roche-Posay 產品分享

中醫養生典籍摘錄