📖 Nginx 伺服器架設

分類:伺服器管理 | 作者:pake | 發布時間:2024-09-03 12:23

學習如何使用 Nginx 設定網站

學習如何使用 Nginx 設定網站

Nginx 是一款高效能的 Web 伺服器,適用於靜態網站、反向代理及負載平衡。本篇將介紹如何在 Fedora 上安裝與設定 Nginx,並以 www.fedora.tw 網站為範例,包含 HTTPS/SSL 設定。


目錄


安裝與啟動 Nginx

安裝 Nginx

sudo dnf install nginx -y

啟動並設定開機自動啟動

sudo systemctl enable --now nginx

檢查 Nginx 服務狀態

sudo systemctl status nginx

如果 Nginx 正常運行,應顯示 active (running)


設定 Nginx 伺服器

Nginx 預設的配置檔案位於 /etc/nginx/nginx.conf,網站配置檔案通常位於 /etc/nginx/conf.d/

編輯主設定檔 /etc/nginx/nginx.conf

確保包含以下內容:

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

events {
    worker_connections 1024;
}

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

    sendfile on;
    keepalive_timeout 65;

    include /etc/nginx/conf.d/*.conf;
}

設定網站 www.fedora.tw

建立網站目錄

sudo mkdir -p /var/www/fedora.tw/html
sudo chown -R nginx:nginx /var/www/fedora.tw

建立首頁文件

echo "<h1>Welcome to Fedora TW</h1>" | sudo tee /var/www/fedora.tw/html/index.html

新增網站設定檔 /etc/nginx/conf.d/fedora.tw.conf

server {
    listen 80;
    server_name www.fedora.tw fedora.tw;

    root /var/www/fedora.tw/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

測試 Nginx 配置並重新啟動

sudo nginx -t
sudo systemctl restart nginx

啟用 SSL / HTTPS

安裝 Certbot 以取得免費 SSL 憑證

sudo dnf install certbot python3-certbot-nginx -y

申請 Let's Encrypt SSL 憑證

sudo certbot --nginx -d www.fedora.tw -d fedora.tw

系統會要求輸入電子郵件並同意 Let's Encrypt 條款,然後自動設定 SSL。

讓憑證自動續期

sudo systemctl enable --now certbot-renew.timer

或手動測試續約:

sudo certbot renew --dry-run

確保 HTTPS 設定在 /etc/nginx/conf.d/fedora.tw.conf

server {
    listen 80;
    server_name www.fedora.tw fedora.tw;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name www.fedora.tw fedora.tw;

    ssl_certificate /etc/letsencrypt/live/www.fedora.tw/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.fedora.tw/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/www.fedora.tw/chain.pem;

    root /var/www/fedora.tw/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

重新啟動 Nginx

sudo nginx -t
sudo systemctl restart nginx

防火牆與 SELinux 設定

開放 HTTP 與 HTTPS 連接埠

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

設定 SELinux

如果 SELinux 啟用,請允許 Nginx 存取網站目錄:

sudo setsebool -P httpd_can_network_connect 1
sudo chcon -R -t httpd_sys_content_t /var/www/fedora.tw

測試與驗證 Nginx 伺服器

確認網站可以存取

打開瀏覽器,訪問:

http://www.fedora.tw
https://www.fedora.tw

檢查 SSL 憑證狀態

openssl s_client -connect www.fedora.tw:443 -servername www.fedora.tw

或使用 SSL Labs 檢查:

https://www.ssllabs.com/ssltest/


結語

本篇介紹了如何在 Fedora 上安裝 Nginx,並以 www.fedora.tw 為範例,說明了如何設定網站、啟用 SSL 憑證、開放防火牆及配置 SELinux。透過這些步驟,您可以成功架設一個安全的 Nginx 伺服器。

⬅ 上一篇 下一篇 ➡
🔙 返回 伺服器管理 📚 返回教學列表 🏠 返回首頁