Ubuntu 22.04 Nginx 網頁伺服器安裝與設定

Ubuntu 22.04 Nginx Install and Configuration

Nginx 是一款高效能的網頁伺服器,以其低資源消耗和高併發處理能力聞名。本文將介紹如何在 Ubuntu 22.04 上安裝與設定 Nginx。

安裝 Nginx

首先更新系統套件庫:

1
sudo apt update

安裝 Nginx:

1
sudo apt install nginx -y

設定防火牆

如果有啟用 UFW 防火牆,需要允許 HTTP 和 HTTPS 流量:

1
2
3
4
5
6
7
8
# 查看可用的應用程式設定檔
sudo ufw app list

# 允許 Nginx 完整存取(HTTP 和 HTTPS)
sudo ufw allow 'Nginx Full'

# 或者只允許 HTTP
sudo ufw allow 'Nginx HTTP'

驗證安裝

檢查 Nginx 服務狀態:

1
sudo systemctl status nginx

在瀏覽器中輸入伺服器 IP 位址,應該會看到 Nginx 預設歡迎頁面。

常用管理指令

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 停止 Nginx
sudo systemctl stop nginx

# 啟動 Nginx
sudo systemctl start nginx

# 重新啟動 Nginx
sudo systemctl restart nginx

# 重新載入設定(不中斷服務)
sudo systemctl reload nginx

# 設定開機自動啟動
sudo systemctl enable nginx

# 停用開機自動啟動
sudo systemctl disable nginx

重要目錄與檔案

路徑說明
/var/www/html/預設網站根目錄
/etc/nginx/Nginx 設定檔目錄
/etc/nginx/nginx.conf主設定檔
/etc/nginx/sites-available/可用的站台設定
/etc/nginx/sites-enabled/已啟用的站台設定
/var/log/nginx/access.log存取日誌
/var/log/nginx/error.log錯誤日誌

設定 Server Block(虛擬主機)

建立網站目錄:

1
2
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html

建立測試頁面:

1
echo "<h1>Welcome to Example.com</h1>" | sudo tee /var/www/example.com/html/index.html

建立 Server Block 設定檔:

1
sudo nano /etc/nginx/sites-available/example.com

加入以下內容:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
server {
    listen 80;
    listen [::]:80;

    root /var/www/example.com/html;
    index index.html index.htm;

    server_name example.com www.example.com;

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

啟用設定:

1
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

測試設定並重新載入:

1
2
sudo nginx -t
sudo systemctl reload nginx

參考資料

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy