Linux WWW 伺服器

Nginx

安裝與執行

# 查詢 nginx 套件(CentOS 8/Stream 或 RHEL 8+ 使用 dnf)
sudo dnf list nginx

# 安裝 nginx
sudo dnf install -y nginx

# 將 80 埠加入防火牆規則並重載
sudo firewall-cmd --add-port=80/tcp --permanent
sudo firewall-cmd --reload

# 啟動並設定開機啟動 nginx
sudo systemctl enable nginx
sudo systemctl start nginx

# 查看 nginx 服務狀態
sudo systemctl status nginx

# 檢查 nginx 是否有監聽 TCP 80 埠
ss -ntulp | grep nginx

# 查看 nginx 版本
nginx -v

網頁預設根目錄

Nginx 預設根目錄為 /usr/share/nginx/html,預設可以用瀏覽器透過 http://127.0.0.1 或伺服器 IP 存取 Nginx 預設歡迎頁。

nginx 設定檔

主要設定檔為 /etc/nginx/nginx.conf,虛擬主機設定通常放在 /etc/nginx/conf.d/ 下的 .conf 檔案。

以下為範例設定,示範如何設定網站根目錄並支援 PHP:

server {
    listen 80;
    server_name MyWeb.com.tw www.MyWeb.com.tw;

    root /var/www/MyWeb;
    index index.php index.html index.htm;

    access_log /var/log/nginx/MyWeb.access.log;
    error_log /var/log/nginx/MyWeb.error.log;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php-fpm/www.sock;
        include fastcgi.conf;
    }

    location ~ /\.ht {
        deny all;
    }
}

設定完成後,可透過以下指令檢查設定是否正確,並重新載入 nginx:

nginx -t

sudo systemctl restart nginx
# 或使用重新載入設定
sudo systemctl reload nginx

Apache

安裝與執行

Apache 伺服器套件名稱為 httpd,安裝並啟動服務步驟如下:

sudo dnf install httpd

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

# 啟動 httpd 服務
sudo systemctl start httpd

# 查看服務狀態
sudo systemctl status httpd

# 確認 httpd 是否監聽 80 埠
ss -ntulp | grep :80

# 防火牆開放 http 服務(包含 80 埠)
sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --reload

# 確認防火牆已開放 http 服務
firewall-cmd --list-all | grep http

網頁預設根目錄

Apache 預設根目錄為 /var/www/html,首頁檔案放在此目錄下。

Apache 設定檔

Apache 虛擬主機設定檔通常放在 /etc/httpd/conf.d/,可自行建立 .conf 檔案管理不同網站。

以下為虛擬主機設定範例:

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/var/www/html/MyWeb"
    ServerName MyWeb.com.tw
    ServerAlias www.MyWeb.com.tw

    ErrorLog "/var/log/httpd/MyWeb.error_log"
    CustomLog "/var/log/httpd/MyWeb.access_log" common

    <Directory "/var/www/html/MyWeb">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

說明:

參數 說明
*:80 監聽埠號為 80
DocumentRoot 網站文件根目錄
ServerAdmin 站台管理者電子郵件
ServerName 主機名稱(FQDN)
ServerAlias 主機別名
ErrorLog 錯誤日誌路徑
CustomLog 訪問日誌路徑

設定修改完後,重新啟動 Apache:

sudo systemctl restart httpd

以上內容是依照 CentOS 8/RHEL 8+ 環境整理,其他 Linux 發行版使用時,請視套件管理工具及路徑稍作調整。