cjxd

cjxd

长恨此身非我有,何时忘却营营

Nginx轉發教程

簡單記錄下轉發 Docker 映射出來的端口以及轉發到別的伺服器上的過程

安裝 Nginx#

1.debain 系統安裝#

sudo apt-get update
sudo apt-get install nginx

2. 驗證 NGINX 是否成功安裝。在終端中輸入以下命令:#

sudo service nginx start

申請 SSL 證書#

1. 獲取 CerBot 客戶端#

install certbot

2. 獲取證書#

certbot certonly --webroot -w /var/www/example -d example.com -d www.example.com

這個命令會為 example.com 和 www.example.com 這兩個域名生成一個證書,使用 --webroot 模式會在 /var/www/example 中創建 .well-known 文件夾,這個文件夾裡面包含了一些驗證文件,certbot 會通過訪問 example.com/.well-known/acme-challenge 來驗證你的域名是否綁定的這個伺服器。這個命令在大多數情況下都可以滿足需求,
滿足需求,

但是有些時候我們的一些服務並沒有根目錄,例如一些微服務,這時候使用 --webroot 就走不通了。certbot 還有另外一種模式 --standalone , 這種模式不需要指定網站根目錄,他會自動啟用伺服器的 443 端口,來驗證域名的歸屬。我們有其他服務(例如 nginx)佔用了 443 端口,就必須先停止這些服務,在證書生成完畢後,再啟用。

certbot certonly --standalone -d example.com -d www.example.com

證書生成完畢後,我們可以在 /etc/letsencrypt/live/ 目錄下看到對應域名的文件夾,裡面存放了指向證書的一些快捷方式。

這時候我們的第一生成證書已經完成了,接下來就是配置我們的 web 伺服器,啟用 HTTPS。

新建轉發配置#

1. 配置 NGINX 反向代理。在終端中輸入以下命令:#

blog.xxxx.xxx我就用域名作為配置文件了

touch /etc/nginx/sites-available/blog.xxxx.xxx

2. 配置文件參考#

這個的意思是轉發到 localhost 的 3000 端口

server {
    listen 80;
    listen [::]:80;
    server_name wqq.xxxx.xxx;
    return 301 https://$server_name$request_uri;
    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
        port_in_redirect off;
        proxy_redirect http://localhost:3000 https://wqq.xxxx.xxx;
        proxy_connect_timeout 300;
        proxy_send_timeout 300;
        proxy_read_timeout 300;
        send_timeout 300;
    }
}
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name wqq.xxxx.xxx;

    ssl_certificate /etc/letsencrypt/live/wqq.xxxx.xxx/fullchain.pem; # 替換成您的證書路徑
    ssl_certificate_key /etc/letsencrypt/live/wqq.xxxx.xxx/privkey.pem; # 替換成您的證書私鑰路徑
    
    # 強制 HTTPS
    if ($scheme != "https") {
        return 301 https://$server_name$request_uri;
    }
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
        port_in_redirect off;
        proxy_redirect http://localhost:3000 https://wqq.xxxx.xxx;
        proxy_connect_timeout 300;
        proxy_send_timeout 300;
        proxy_read_timeout 300;
        send_timeout 300;
    }
}

3. 開啟 sites-enabled 的軟連結#

之後需要在 /etc/nginx/sites-enabled 用符號連結鏈接到上述 /etc/nginx/sites-available/blog.xxxx.xxx 文件,命令如下:

ln -s /etc/nginx/sites-available/blog.ryujinx.top /etc/nginx/sites-enabled/

然後檢查 nginx 配置文件是否正確:sudo nginx -t, 如果提示 "Syntax OK" 說明配置正確,再執行 sudo systemctl reload nginx 重啟 nginx,就完成了配置。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。