如何为使用 nginx 的多个应用程序使用自定义位置或路径而不是 root? [英] How to use custom location or path instead root for several apps using nginx?

查看:13
本文介绍了如何为使用 nginx 的多个应用程序使用自定义位置或路径而不是 root?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,它在像 mydomain.com 这样的根域上运行良好,无需任何修改.但是,如果我想将其作为 mydomain.com/app1 使用,我需要修改后端中的源代码和 html 中的静态链接(css、图像等)

I have a web which works fine on a root domain like mydomain.com without any modification. But if I want to serve it as mydomain.com/app1 I I need to modify the source code in the backend and statics links (css, images, etc) in the html

  • 节点:
    • app.get('/')app.get('/app1')
    • src=main.css"src=app1/main.css"

    当我想使用 nginx 分配域/路径时,我应该总是修改应用程序吗?

    Should I always modify the application when I want to assign a domain/path using nginx?

    https://github.com/jrichardsz/nodejs-static-pages/blob/master/server.js

    app.get('/', function(req, res) {
        // ejs render automatically looks in the views folder
        res.render('index');
    });
    

    用于根域的 Nginx

    这是我的 nginx 配置,适用于 mydomain.com

    server {
      listen 80;
      server_name mydomain.com;
     
      location / {
        proxy_pass http://localhost:8080/;
      }
    }
    

    尝试 mydomain.com/app1

    server {
      listen 80;
      server_name mydomain.com;
      
      location /app1/ { 
        proxy_pass http://localhost:8080/app1/; 
      }
    }
    

    这是 node js 应用程序中的修复

    And this is the fix in node js app

    app.get('/app1', function(req, res) {
        // ejs render automatically looks in the views folder
        res.render('index');
    });
    

    我试过了:

    https://github.com/expressjs/express-namespace

    http://expressjs.com/en/4x/api.html

    但在这两种情况下,我都需要更改我的节点 js 应用程序.

    But in both cases, I need change my node js app.

    提前致谢.

    推荐答案

    当您要分配域/路径时,是否应该始终修改应用程序?

    Should you always modify the application when you want to assign a domain/path?

    不,您根本不需要修改应用程序.

    No, you shouldn't have to modify the application at all.

    当你以这种方式使用proxy_pass时,你需要用正则表达式重写URL.尝试这样的事情:

    When you use proxy_pass in this manner, you need to rewrite the URL with regex. Try something like this:

      location ~ ^/app1/(.*)$ { 
        proxy_pass http://localhost:8080/$1$is_args$args; 
      }
    

    另见:https://serverfault.com/q/562756/52951

    这篇关于如何为使用 nginx 的多个应用程序使用自定义位置或路径而不是 root?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆