BrowserSync: Proxy Subdomains

你。 提交于 2020-12-13 04:09:28

问题


I have a Django app which serves multiple sites on separate subdomains. In development, I access the sites on:

  • www.myapp.local:8000
  • data.myapp.local:8000
  • publish.myapp.local:8000
  • admin.myapp.local:8000

Note this works using the django_hosts library and through modifying /etc/hosts file, e.g:

127.0.0.1 www.myapp.local
127.0.0.1 data.myapp.local
127.0.0.1 publish.myapp.local
127.0.0.1 admin.myapp.local

However, I am unable to figure out how to configure BrowserSync, in my Gulp-based workflow, in order to proxy all subdomains, providing a seamless experience as I navigate around the sites, and reload the browser as I develop.

Configuring BrowserSync to proxy the main site, e.g.

browserSync.init(
    [paths.css + "/*.css", paths.js + "*.js", paths.templates + '/**/*.html'], {
    proxy: 'www.myapp.local:8000' 
})

only 'captures' the main site, if you click a link to one of the subdomains, you navigate out of the BrowserSync session and will be served directly by Django on port 8000.


回答1:


Got this to work perfectly using a combination of middleware (using http-proxy-middleware) and rewriteRules:

const proxy = require('http-proxy-middleware'),

browserSync.init([paths.css + "/*.css", paths.js + "*.js", paths.templates + '/**/*.html'], {
    middleware: [
        function (req, res, next) {
            let target = 'http://' + req.headers.host.replace('myapp.local:3000', 'myapp.local:8000');
            proxy({
                target,
                changeOrigin: true
            })(req, res, next);
        }
    ],
    rewriteRules: [
        {
            match: /myapp.local:8000/g,
            fn: function (req, res, match) {
                return 'myapp.local:3000';
            }
        }
    ]
});

The middleware matches any url with the parent domain,myapp.local:3000, and proxies the request to port 8000 listened to by Django without changing the subdomain. The rewriteRules are used to rewrite any links in the response, so subsequent navigation is correctly reversed back through the proxy.



来源:https://stackoverflow.com/questions/56295613/browsersync-proxy-subdomains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!