想替換 Apache 改用 Nginx?本文詳述從下載原始碼、安裝依賴、編譯安裝、啟動管理、多站點虛擬主機配置、自定義 404/50x 錯誤頁面,到常見錯誤(80 埠佔用、worker_connections 警告)的解決方案。
wget https://nginx.org/download/nginx-1.5.2.tar.gztar zxvf nginx-1.5.2.tar.gz && cd nginx-1.5.2yum -y install gcc gcc-c++ autoconf automake zlib zlib-devel openssl openssl-devel pcre-develgroupadd -r nginx && useradd -s /sbin/nologin -g nginx -r nginx./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_modulemake && make install/usr/local/nginx/sbin/nginx(或依 configure 指定路徑)/usr/local/nginx/sbin/nginx -s reload/usr/local/nginx/sbin/nginx -tmkdir /usr/local/nginx/conf/vhostvi /usr/local/nginx/conf/vhost/example.confnginx.conf http 區塊加入:include vhost/*.conf;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.html、50x.html 放於網站根目錄。nginx.conf http 區塊加入:fastcgi_intercept_errors on;error_page 404 /404.html; 或 error_page 404 =https://example.com/404.html;error_page 500 502 503 504 /50x.html;注意: 404 頁面需大於 512 bytes,否則 IE 會顯示預設錯誤頁;勿將首頁設為 404 頁面。
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 → 重新啟動。
[warn] 51200 worker_connections are more than open file resource limit: 51200系統開啟檔案數限制過低。ulimit -n 51200 (臨時)或修改 /etc/security/limits.conf 永久生效,再重新載入 Nginx。
等級由詳細到少:debug | info | notice | warn | error | crit。
關閉錯誤日誌:error_log /dev/null crit;(非 off)。