Making a WordPress site accesible from inside LAN and outside it

Pijuli picture Pijuli · Feb 23, 2015 · Viewed 7.1k times · Source

I configured WordPress on a PC inside my LAN. So I can access it from the same computer with localhost/WordPress or another pc on the LAN with IP/WordPress.

I configured the router so port 80 is redirected to the server IP, but if a page is loaded from outside my LAN, it fails to load CSS and JS as the route is localhost on WordPress config. If I change it to my freedns url, let's say: myamazingurl.mooo.com, it is accessible from outside my LAN and it loads CSS and JS.

Now I can't access my website from inside the LAN. Is there any workaround or fix for that?

I read about dnsmasq but I didn't succeed.

Answer

Lafif Astahdziq picture Lafif Astahdziq · Sep 23, 2015

the main issue is because wordpress use the server address from database.

WordPress uses the root url from the option named home and siteurl so if you try access WordPress outside their computer it might get the incorrect path for css and javascript.

you need to change the options under setting -> general and fill in the WordPress Address (URL) and the Site address (URL) with your server IP

if you want to get correct path without doing redirect, you can defining the dynamic root url under wp-config.php

add this script below the define('ABSPATH', dirname(__FILE__) . '/');

/**
 * get home url from absolute path
 * @return string url to main site
 * [email protected]
 */
function get_dynamic_home_url(){
    $base_dir  = ABSPATH; // Absolute path
    $doc_root  = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']);
    $base_url  = preg_replace("!^${doc_root}!", '', $base_dir);
    $protocol  = empty($_SERVER['HTTPS']) ? 'http' : 'https';
    $port      = $_SERVER['SERVER_PORT'];
    $disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
    $domain    = $_SERVER['SERVER_NAME'];
    $home_url  = "${protocol}://${domain}${disp_port}${base_url}";

    return $home_url;
}
$url = get_dynamic_home_url();
define('WP_SITEURL', $url);
define('WP_HOME', $url);