您好,登录后才能下订单哦!
# 如何在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。