Created
February 21, 2021 21:13
-
-
Save alexandreelise/7a1a95be32710454413919ed7b9ad970 to your computer and use it in GitHub Desktop.
Replace wildcard IPv4 address in your Nginx config files by 127.0.0.1 to try to prevent remote access by internet users to you local dev virtuelhosts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
/** | |
* This php script attempts to replace wildcard IPv4 address in Nginx sites-available/*.conf files | |
* by the loopback address 127.0.0.1 to try to prevent access of your local dev environment by Internet | |
* when listening to all network interface like *:80 or *:443 does. * means listen to all available network | |
* interfaces and this script tries to restrict use to loopback only. | |
* | |
* NOTE: If you have multiple wildcard IPv4 address in your conf files at the moment of writing this script it | |
* doesn't handle yet this edge case correctly. It just replaces all the wildcard addresses rather than having just one occurence of 127.0.0.1 you will have multiple ones which can cause "address already in use" errors while restart Nginx. Please keep that in mind. You can improve this script at will. It's a first attempt. Hope it helps someone. | |
* | |
* @package force-localhost-site | |
* @author Alexandre ELISÉ <[email protected]> | |
* @copyright (c) . Alexandre ELISÉ . Tous droits réservés. | |
* @license MIT | |
* @link https://coderparlerpartager.fr | |
*/ | |
$sites = glob("/etc/nginx/sites-available/*.conf"); | |
foreach ($sites as $site) | |
{ | |
$content = file_get_contents($site); | |
// attempting to replace wildcard ipv4 address to 127.0.0.1 address to prevent listening on wildcard | |
// on any interface and rather listen on loopback only | |
$result = preg_replace('/listen([\s\t]+)(\*|(([0*])\.([0*])\.([0*])\.([0*])))\:/', 'listen 127.0.0.1:', $content); | |
// if there is an error attempting to replace | |
if ($result === null) | |
{ | |
echo 'ko' . PHP_EOL; | |
} | |
elseif ($result !== $content) // something has been replaced | |
{ | |
file_put_contents($site, $result); | |
echo 'ok' . PHP_EOL; | |
} | |
else // nothing changed | |
{ | |
echo 'eq' . PHP_EOL; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment