简体   繁体   中英

How to have dynamic .env files instead of hard coded localhost?

I have 2 .env files (one for Vue and one for Laravel). Both of them have localhost hard coded inside of them. That means that I can't access my application from another computer on my network. It would be nice if it was dynamic (except for production)

For example if I go to my other PC and access my site at http://192.168.1.100:47344 then it won't work because it is hardcoded to localhost (escpecially frontend calls) .

But I can't write javascript or PHP inside .env files to change localhost to something like window.location.host and for PHP $_SERVER['SERVER_ADDR'] . I can't find the solultion..

My Vue .env

VITE_SERVER_URL=http://localhost:41166
VITE_APP_ENV=dev

And my Laravel .env

APP_ENV=local
APP_CLIENT_URL=http://localhost:47344
APP_URL=http://localhost:41166

Even if your app url is set to localhost , the application is still accessible, as long as there is no firewall restricting it. You can also access it through 127.0.0.1 or the local IP address assigned to your machine.


The way to get your local ip address depends on your system, but you can just run this in the node console

const { networkInterfaces } = require("os");
const nets = networkInterfaces();

for (const name of Object.keys(nets)) {
  for (const net of nets[name]) {
    if (net.family === "IPv4" && !net.internal) {
      console.log({name , address: net.address});
    }
  }
}

Note that if you're running this in docker the setting may need to be 0.0.0.0 because 127.0.0.1 is a loopback host.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM