萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 從原始碼編譯安裝 Nginx Web 伺服器完整教學(含多站點、404 自定義、常見錯誤處理)

想替換 Apache 改用 Nginx?本文詳述從下載原始碼、安裝依賴、編譯安裝、啟動管理、多站點虛擬主機配置、自定義 404/50x 錯誤頁面,到常見錯誤(80 埠佔用、worker_connections 警告)的解決方案。

編譯安裝步驟

  1. 下載與解壓
    wget https://nginx.org/download/nginx-1.5.2.tar.gz
    tar zxvf nginx-1.5.2.tar.gz && cd nginx-1.5.2
  2. 安裝編譯依賴
    yum -y install gcc gcc-c++ autoconf automake zlib zlib-devel openssl openssl-devel pcre-devel
  3. 建立 nginx 使用者/群組
    groupadd -r nginx && useradd -s /sbin/nologin -g nginx -r nginx
  4. 配置編譯參數(或用預設 ./configure)
    ./configure --prefix=/usr --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx/nginx.pid --user=nginx --group=nginx --with-http_ssl_module --with-http_flv_module --with-http_gzip_static_module --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/tmp/nginx/client --http-proxy-temp-path=/var/tmp/nginx/proxy --http-fastcgi-temp-path=/var/tmp/nginx/fcgi --with-http_stub_status_module
  5. 編譯安裝
    make && make install

服務管理指令

  • 啟動:/usr/local/nginx/sbin/nginx(或依 configure 指定路徑)
  • 重新載入配置:/usr/local/nginx/sbin/nginx -s reload
  • 測試配置:/usr/local/nginx/sbin/nginx -t

多站點配置(虛擬主機)

  1. 建立 vhost 目錄:mkdir /usr/local/nginx/conf/vhost
  2. 建立站點配置檔:vi /usr/local/nginx/conf/vhost/example.conf
  3. 在 nginx.conf http 區塊加入:include vhost/*.conf;
  4. 重新載入 Nginx

站點配置範例

server {
    listen 80;
    server_name example.com www.example.com;
    index index.html index.php;
    root /www/example;
    include emlog.conf;
    location ~ [^/]\.php(/|$) {
        try_files $uri =404;
        fastcgi_pass unix:/tmp/php-cgi.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; }
    location ~ .*\.(js|css)?$ { expires 12h; }
    access_log /home/wwwlogs/example.com.log access;
}

自定義 404/50x 錯誤頁面

  1. 建立 404.html、50x.html 放於網站根目錄。
  2. 在 nginx.conf http 區塊加入:fastcgi_intercept_errors on;
  3. 在 server 區塊加入:error_page 404 /404.html; 或 error_page 404 =https://example.com/404.html;
  4. error_page 500 502 503 504 /50x.html;
  5. 重新載入 Nginx 生效。

注意: 404 頁面需大於 512 bytes,否則 IE 會顯示預設錯誤頁;勿將首頁設為 404 頁面。

常見錯誤與解決

1. bind() to 0.0.0.0:80 failed (98: Address already in use)

80 埠被佔用(通常是殘留 nginx 進程)。
lsof -i:80 找出 PID → kill -9 PID 或 killall -9 nginx → 重新啟動。

2. [warn] 51200 worker_connections are more than open file resource limit: 51200

系統開啟檔案數限制過低。
ulimit -n 51200 (臨時)或修改 /etc/security/limits.conf 永久生效,再重新載入 Nginx。

3. error_log 配置

等級由詳細到少:debug | info | notice | warn | error | crit。
關閉錯誤日誌:error_log /dev/null crit;(非 off)。

copyright © 萬盛學電腦網 all rights reserved