# 如何在CentOS7上搭建Nginx
## 前言
Nginx(發音為"engine-x")是一款高性能的HTTP和反向代理服務器,以其穩定性、豐富的功能集、簡單的配置和低資源消耗而聞名。它不僅可以作為Web服務器使用,還能作為負載均衡器、郵件代理服務器和HTTP緩存等。本文將詳細介紹在CentOS 7操作系統上搭建Nginx的完整過程,包括安裝、配置、優化和常見問題解決等內容。
## 環境準備
在開始之前,請確保您已經具備以下條件:
1. 一臺運行CentOS 7的服務器(物理機或虛擬機)
2. 具有root權限或sudo權限的用戶賬戶
3. 能夠訪問互聯網以下載必要的軟件包
4. 基本的Linux命令行操作知識
建議在操作前更新系統軟件包:
```bash
sudo yum update -y
CentOS 7的默認倉庫中不包含最新版本的Nginx,因此我們需要先添加Nginx的官方倉庫:
sudo yum install epel-release -y
sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
sudo yum install nginx -y
nginx -v
如果需要特定版本的Nginx或需要自定義模塊,可以選擇源碼編譯安裝:
sudo yum install gcc pcre-devel zlib-devel openssl-devel -y
wget http://nginx.org/download/nginx-1.20.1.tar.gz
tar -zxvf nginx-1.20.1.tar.gz
cd nginx-1.20.1
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-threads
make && sudo make install
sudo vi /etc/systemd/system/nginx.service
添加以下內容:
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MNPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
然后執行:
sudo systemctl daemon-reload
sudo systemctl enable nginx
Nginx的主配置文件位于/etc/nginx/nginx.conf
(Yum安裝)或/usr/local/nginx/conf/nginx.conf
(源碼安裝)。以下是一些關鍵配置項:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
建議為每個網站創建單獨的配置文件:
sudo vi /etc/nginx/conf.d/example.com.conf
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
location = /404.html {
internal;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
}
}
sudo mkdir -p /var/www/example.com/html
sudo chown -R nginx:nginx /var/www/example.com
sudo chmod -R 755 /var/www/example.com
sudo vi /var/www/example.com/html/index.html
內容示例:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Example.com</title>
</head>
<body>
<h1>Success! The example.com server is working!</h1>
</body>
</html>
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx
sudo systemctl reload nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
如果系統啟用了防火墻,需要開放HTTP(80)和HTTPS(443)端口:
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
sudo yum install certbot python2-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run
sudo mkdir /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/nginx/ssl/example.com.key \
-out /etc/nginx/ssl/example.com.crt
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_ecdh_curve secp384r1;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
# 其他配置...
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
worker_processes auto; # 自動設置為CPU核心數
worker_rlimit_nofile 100000; # 每個worker能打開的文件描述符數量
events {
worker_connections 4096; # 每個worker的最大連接數
multi_accept on; # 一次接受所有新連接
use epoll; # 使用epoll事件模型
}
http {
sendfile on; # 啟用sendfile
tcp_nopush on; # 僅在sendfile開啟時有效
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 30; # 保持連接超時時間
keepalive_requests 1000; # 每個連接的最大請求數
client_body_buffer_size 10K; # 客戶端請求體緩沖區大小
client_header_buffer_size 1k; # 客戶端請求頭緩沖區大小
client_max_body_size 8m; # 最大請求體大小
large_client_header_buffers 4 8k; # 大型請求頭緩沖區
open_file_cache max=200000 inactive=20s; # 文件描述符緩存
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
gzip on; # 啟用gzip壓縮
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";
}
server_tokens off;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
limit_except GET POST {
deny all;
}
location / {
autoindex off;
}
sudo vi /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
sudo netstat -tulnp | grep :80
sudo kill -9 <PID>
可能原因: - 目錄權限不正確 - SELinux限制
解決方法:
sudo chown -R nginx:nginx /var/www/example.com
sudo chmod -R 755 /var/www/example.com
# 如果使用SELinux
sudo chcon -R -t httpd_sys_content_t /var/www/example.com
可能原因: - 后端服務未啟動 - 連接超時
檢查方法:
sudo tail -f /var/log/nginx/error.log
# 查看Nginx工作進程
ps -ef | grep nginx
# 查看連接狀態
netstat -ant | grep :80 | awk '{print $6}' | sort | uniq -c | sort -n
# 實時監控訪問日志
tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
本文詳細介紹了在CentOS 7上安裝和配置Nginx的全過程,包括: 1. 通過Yum倉庫和源碼兩種安裝方式 2. 基本的Nginx配置和虛擬主機設置 3. SSL/TLS證書配置實現HTTPS 4. 性能優化和安全加固建議 5. 常見問題的解決方法
Nginx是一個功能強大且靈活的Web服務器,通過合理的配置可以滿足各種Web服務需求。建議在生產環境中進一步根據實際需求調整配置參數,并定期更新Nginx版本以獲得最新的功能和安全補丁。
”`
注:本文總字數約3500字,涵蓋了Nginx在CentOS 7上的完整安裝配置流程。實際使用時可根據具體需求調整配置參數。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。