本文主要介绍如何将打包好的前端静态文件放到云服务器,并配置 nginx 服务进行对应的端口访问。
- 安装 nginx
- 上传打包文件
- 配置 nginx 端口访问
云服务器下载 nginx
官方下载 ubuntu 步骤
执行 nginx -v 可以获得版本号,说明安装成功
ubuntu:/$ nginx -v
nginx version: nginx/1.24.0
nginx 配置说明
配置文件地址: /etc/nginx/nginx.conf
查看配置文件: cat /etc/nginx/nginx.conf
文件里面这行:
include /etc/nginx/conf.d/*.conf; # 说明这个 `conf.d` 下的所有文件都会被应用到
在 /etc/nginx/conf.d 目录下有个 default.conf 文件,启动 nginx sudo nginx 后,访问网页根目录就可以看到下面的页面:
下面是 default.conf 文件的内容
server {
listen 80; # 监听 80 端口
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html; // index 文件路径
index index.html index.htm; // index 目录文件名
}
}
我们找到 /usr/share/nginx/html/index.html 内容如下
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
此文件就是上面看到的访问 80 端口所看到文件
上传本地文件至云服务器
从本地上传文件到云服务器主要使用的是 scp 命令
# 从本地上传文件到远端,示例
scp -r /home/test/dist/ ubuntu@www.runoob.com:/data/www/xx/
如果遇到 Permission denied, 可能是你登录在云服务器的用户没有目录权限,比如上方的 ubuntu 用户没有 /data/www 的权限,则需要给 ubuntu 加 data 目录的权限
ubuntu@aaa: ls -al / # 查看当前所有用户的各个文件权限
> drwxr-xr-x 3 root root 4096 Jun 13 2022 data # 只有 root 用户有权限
ubuntu@aaa: sudo chown -R ubuntu.ubuntu /data # 给 ubuntu 加权限
此时再次在本地执行 scp xxx 上传命令就可以正常传文件了。
配置 3000 端口访问打包的文件
假设现在前端打包后的文件已经放在了 /data/www/test 目录下,index.html 文件在此目录下。
我们给 nginx 配置一个 3000 端口指向此目录的文件: test.conf
# test.conf
server {
listen 3000; # 监听 3000 端口
server_name localhost;
location / {
root /data/www/test; // index 文件路径
index index.html index.htm; // index 目录文件名
}
}
将 test.conf 放在 /etc/nginx/conf.d 目录下,然后重新加载下 nginx 的配置文件 sudo nginx -s reload,打开域名地址,访问 3000 端口,就可以看到类似下面的前端页面展示
如果访问 3000 看不到这个页面,可能是你的云服务器防火墙没有打开 3000 端口。