Nodejs 前端程序通过 Nginx 部署后刷新出现 404 问题的解决办法

方案一 (这种方式容易被第三方劫持)

location / {
        root /data/nginx/html;
        index index.html index.htm;
        error_page 404 /index.html;
}

方案二

location / {
    root /data/nginx/html;
    index index.html index.htm;
    if (!-e $request_filename) {
        rewrite ^/(.*) /index.html last;
        break;
    }
}

方案三 (vue.js官方教程里提到的https://router.vuejs.org/zh-cn/essentials/history-mode.html

server {
    listen 80;
    server_name localhost;
    root /data/wwwroot/dist;
    location / {
        try_files $uri $uri/ @router;
        index index.html index.htm;
    }
    location @router {
        rewrite ^.*$ /index.html last;
    }
}

或者

location / {
    try_files $uri $uri/ /index.html;
}

参考以下两位大神的博客:

https://blog.csdn.net/u011025083/article/details/80352301
https://www.jianshu.com/p/02ad1f919471

要将Node.js应用程序部署Nginx上,您可以按照以下步骤进行操作: 1. 安装Node.js:首先,确保您在服务器上安装了Node.js。您可以从Node.js官方网站下载并安装适合您操作系统的Node.js版本。 2. 启动Node.js应用程序:在服务器上,使用Node.js命令启动您的应用程序。例如,如果您的应用程序入口文件为`app.js`,可以使用以下命令启动应用程序: ``` node app.js ``` 3. 配置Nginx代理:现在,您需要配置Nginx以将传入的HTTP请求代理到Node.js应用程序。 - 打开Nginx配置文件(通常是`/etc/nginx/nginx.conf`或`/etc/nginx/conf.d/default.conf`)。 - 在`server`块内添加以下配置: ``` location / { proxy_pass http://localhost:3000; # 将端口3000替换为您应用程序实际运行的端口 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } ``` - 保存并关闭配置文件。 4. 重新启动Nginx:使用适合您的操作系统的命令重新启动Nginx服务。例如,对于Ubuntu,可以使用以下命令: ``` sudo service nginx restart ``` 现在,您的Node.js应用程序应该通过Nginx代理进行访问。您可以使用服务器的IP地址或域名来访问应用程序。请确保您的应用程序正在监听与Nginx配置文件中指定的端口相同的端口。在上述示例中,应用程序应该在端口3000上运行。 请注意,这只是最基本的配置示例。根据您的需求和应用程序的特定要求,您可能需要进行其他配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值