Reputation: 395
I am using browsersync together with mkcert and virtual hosts (on Windows) to proxy a live site living at https://www.example.com.
My goal is to proxy the site https://www.example.com, resolve it to 127.0.0.1 through virtual hosts and inject a JS script. The site https://www.example.com is a client site that I have limited access to (cannot change DNS settings).
This is my current browsersync code:
const browserSync = require("browser-sync").create();
browserSync.init({
proxy: "https://www.example.com", // Original site
https: {
key: "./cert/example.com+4-key.pem",
cert: "./cert/example.com+4.pem",
},
serveStatic: ["./local-scripts"],
files: ["./local-scripts/**/*"],
rewriteRules: [
{
match: /<\/body>/i,
fn: (req, res, match) => `<script src="/your-script.js"></script>${match}`,
},
],
open: false, // Disable auto-opening browser
host: "example.com", // Use the virtual host
port: 443,
middleware: [
(req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");
next();
}
]
});
This is my entry in the hosts file (Windows)
127.0.0.1 example.com
With mkcert I have created certificates for example.com www.example.com "*.example.com" and localhost.
After running ipconfig /flushdns
and opening up https://example.com, the site is proxied well and my script is also injected.
However, I am getting a lot of errors from external scripts since my proxied origin is not the same as the live origin (locally I have no www - or at least I think that's what it is):
Access to XMLHttpRequest at 'https://www.example.com/Magento/test.html' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried setting the host
property in browsersync to www.example.com and also changing the hosts entry to 127.0.0.1 www.example.com
but the site keeps loading without results. DNS flushing doesn't work and when pinging the URL: ping https://www.example.com
it correctly resolves to 127.0.0.1.
I have also tried setting up an alias in the hosts file as: 127.0.0.1 example.com www.example.com
and a mixture of other combinations but nothing seems to be working (inverted main and alias domains, main and alias domains on separate lines).
My guess is that I am doing something wrong but also when searching around issues with virtual host and browsersync, none of the URLs were having www in front. Using domains such as test.example.com work perfectly fine then.
So is this even possible to do with www.?
Thanks!
Upvotes: 0
Views: 14