Nginx部署web站点
qinsz 1/16/2024 ubuntunginxweb
# 一、场景
利用nginx将资源部署到服务器,实现网络内其它计算机通过浏览器访问到web资源
下面以ubuntu系统为例
1
2
2
# 二、实施步骤
# 1. 安装
sudo apt update
sudo apt install nginx
1
2
2
# 2. 启动nginx
通过apt安装后,会自动启动,一般不需要手动start
sudo systemctl start nginx
1
# 3. 查看nginx状态
sudo systemctl status nginx
1
# 4. 重启nginx
在每次修改配置文件后,都需要使用重启指令,让nginx配置生效
sudo systemctl restart nginx
1
# 5. 添加web服务
即部署web资源
- 在/etc/nginx/conf.d路径下创建一个以conf为后缀的配置文件
cd /etc/nginx/conf.d/ sudo vim my_web.conf1
2 - 进入my_web.conf文档的编辑界面后,添加如下内容
server{ listen 9090; root /home/cqcet/webs/env_web; location / { index index.html; } }1
2
3
4
5
6
7- listen:表示配置监听端口
- root:指向需要部署的web资源的根目录
- location:配置url路径,里面的index表示指定web资源的入口文件
# 6. 将web资源拷贝至目标路径
因为在本例上一步的my_web.conf配置文件中配置的root路径为 /home/cqcet/web/env_web 因此需要将web资源拷贝到该路径下。如果完成拷贝工作,那么cd到该路径下,通过ls指令查看内容则可以看到有一份index.html文件以及其它的资源文件。
cd /home/cqcet/web/env_web
ls
cfg.js favicon.ico index.html static
1
2
3
2
3
# 7. 检查nginx配置
当my_web.conf文件配置完成,并将web资源拷贝到了所配置的路径下之后。可通过nginx的-t指令来检查配置的正确性
sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
1
2
3
2
3
如果看到syntax is ok和test is successful的提示,表示配置无误。
# 8. 配置生效
通过重启nginx服务使得配置生效
sudo systemctl restart nginx
1
# 9. 访问web站点
使用nginx服务所在的服务器ip地址+端口号,如: http://192.168.1.100:9090
# 10. 403错误
如果访问的时候出现403错误,说明nginx进程没有访问资源文件的权限。简单的做法是修改nginx的配置文件,将nginx的启动用户修改为具备权限的用户,比如资源文件所在的用户,或者直接修改为root
- 进入编辑模式
sudo vim /etc/nginx/nginx.conf1 - 将文件顶部的user值修改为root或其它具备权限的用户
user root; worker_processes auto;1
2