阿里云安装配置Nginx
#nginx
#server
#阿里云
#ecs
背景说明
在上一篇文章中我们更新了CentOS 8的yum源,接下来我们将使用yum来安装Nginx。Nginx是一个高性能的HTTP和反向代理服务器,在Web应用部署中使用广泛。
在阿里云服务器上安装Nginx作为Web服务器,可以用来部署网站、反向代理等。本文记录了在CentOS系统上安装和配置Nginx的完整过程。
安装步骤
1. 安装EPEL仓库
首先需要安装EPEL(Extra Packages for Enterprise Linux)仓库,因为Nginx包在这个仓库中:
1
| yum install epel-release -y
|
2. 安装Nginx
安装Nginx软件包:
3. 启动Nginx服务
启动Nginx服务并设置开机自启:
1 2
| systemctl start nginx systemctl enable nginx
|
配置说明
Nginx的主配置文件位于:
安装完成后,可以通过服务器IP地址访问Nginx默认页面,验证安装是否成功。
常用命令
一些常用的Nginx服务控制命令:
- 启动Nginx:
systemctl start nginx
- 停止Nginx:
systemctl stop nginx
- 重启Nginx:
systemctl restart nginx
- 重新加载配置:
systemctl reload nginx
- 查看状态:
systemctl status nginx
Nginx配置详解
1. root与alias的区别
在配置静态文件访问时,root和alias是两个重要的指令,它们的主要区别是:
root: 会将完整的URL路径附加到指定目录
1 2 3 4
| location /images/ { root /data/www; }
|
alias: 只使用location后的URL部分
1 2 3 4
| location /images/ { alias /data/www/; }
|
2. 前端路由配置
在部署前端单页应用(SPA)时,需要特别配置Nginx以支持前端路由。这是因为SPA通常使用HTML5 History模式进行路由管理,所有的路由都需要重定向到index.html。
Vue.js应用配置
对于Vue.js应用,典型的配置如下:
1 2 3 4 5
| location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; }
|
React应用配置
React应用的配置类似:
1 2 3 4 5 6 7 8 9 10
| location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; add_header Cache-Control "no-cache, no-store, must-revalidate"; add_header Pragma "no-cache"; add_header Expires "0"; }
|
常见问题解决
- 刷新404问题
如果刷新页面时出现404,通常是因为缺少了try_files
指令:
1 2 3
| location / { try_files $uri $uri/ /index.html; }
|
- 静态资源缓存
为静态资源添加缓存配置:
1 2 3 4 5 6 7 8 9 10 11 12
| location /static/ { root /usr/share/nginx/html; expires 1d; add_header Cache-Control "public, no-transform"; }
location /api/ { add_header Cache-Control "no-cache, no-store, must-revalidate"; proxy_pass http://backend-server; }
|
- 开启Gzip压缩
1 2 3 4 5 6 7
| gzip on; gzip_min_length 1k; gzip_comp_level 6; gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml; gzip_vary on; gzip_proxied any;
|
完整配置示例
这是一个包含了常用配置的完整示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| server { listen 80; server_name example.com;
root /usr/share/nginx/html; index index.html index.htm;
location / { try_files $uri $uri/ /index.html; add_header Cache-Control "no-cache, no-store, must-revalidate"; }
location /static/ { expires 1d; add_header Cache-Control "public, no-transform"; }
location /api/ { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
|
这个配置涵盖了:
- 前端路由支持
- 静态资源缓存
- API代理
- Gzip压缩
- 错误页面处理
使用这个配置可以满足大多数前端项目的部署需求。记得根据实际项目需求调整相关参数。