1. 安装 Nginx
输入一下命令
sudo apt update
sudo apt install nginx
2. 检查 Nginx 安装状态
sudo systemctl status nginx
如果 Nginx 正在运行,你会看到类似如下的输出:
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2025-02-05 12:34:56 UTC; 1min 23s ago
...
3. 上传 vue 页面文件
编译 vue 项目生成的 dist 目录文件,可以使用 WinScp 上传(也可以使用其他方法) 。
使用 sudo 将 dist 目录文件移动到 /var/www 目录:
sudo mv ~/dist /var/www/
4. 配置 Nginx(使用普通用户)
4.1 创建配置文件目录
虽然普通用户不能直接修改 /etc/nginx 下的文件,但可以在自己的主目录下创建配置文件,然后使用 sudo 移动到正确的位置。首先,在主目录下创建一个配置文件目录:
mkdir ~/nginx-config
4.2 创建简单的 Nginx 配置文件
使用文本编辑器(如 nano 或 vim)在该目录下创建一个配置文件,例如 example.conf:
vi ~/nginx-config/example.conf
在文件中添加以下简单的配置内容:
server {
listen 80;
server_name _;
location / {
root /var/www/dist;
index index.html;
try_files $uri $uri/ /index.html; # 解决vue刷新404的问题
}
location /api/ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,token';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
add_header 'Cache-Control' 'no-cache';
if ($request_method = 'OPTIONS') {
return 200;
}
proxy_pass http://192.168.6.241:8080/; # 反向代理
}
}
4.3 移动配置文件到 Nginx 配置目录
使用 sudo 将配置文件移动到 Nginx 的可用站点目录:
sudo mv ~/nginx-config/example.conf /etc/nginx/sites-available/
4.4 创建软链接到启用站点目录
为了让 Nginx 使用这个配置文件,需要在 sites-enabled 目录下创建一个软链接:
sudo ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/
4.5 检查配置文件语法
在重新加载 Nginx 之前,最好检查一下配置文件的语法是否正确:
sudo nginx -t
如果语法正确,你会看到类似如下的输出:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
5. 运行 Nginx
5.1 重新加载 Nginx 配置
如果配置文件语法检查通过,可以重新加载 Nginx 配置,使新配置生效:
sudo systemctl reload nginx
5.2 验证 Nginx 是否正常工作
在浏览器中访问 http://服务器IP地址(将 服务器IP地址 替换为你的服务器实际 IP 地址),如果看到你在 /var/www/dist 目录下放置的自定义页面,说明 Nginx 已经成功运行。
6. 管理 Nginx 服务
普通用户可以使用 sudo 来管理 Nginx 服务,例如:
- 启动 Nginx:
sudo systemctl start nginx
- 停止 Nginx:
sudo systemctl stop nginx
- 重启 Nginx:
sudo systemctl restart nginx
通过以上步骤,你就可以使用普通用户在 Ubuntu 服务器上安装、配置和运行 Nginx。