WordPress under Magento multistore

This is a ‘Note to Self’ as much as anything else. It’s explains how we got the WordPress install to work on a Magento multistore using country stub directories.

The SO question it relates to is here;

http://stackoverflow.com/questions/32613815/htaccess-wordpress-under-magento-site-with-multi-language-sub-directories

We have this in production, hopefully this answer might help someone at some point.

The way we’ve done this is to add a RUN_CODE environmental variable which is used in a custom WordPress filter to get the urls all working. I’ve used the ‘eu’ example from my question to illustrate it below. Note we had to do this for both Apache and Nginx so I’ve added the .htaccess and server blocks for both.

APACHE – .htaccess

In the `eu` country stub subdirectory you add this to your .htaccess file (so eu/.htaccess)

    RewriteCond %{REQUEST_URI} ^/eu/wordpress$
    RewriteRule ^(.*)$ /eu/wordpress/ [R=301]

    RewriteCond %{REQUEST_URI} ^/eu/wordpress(.*)$
    RewriteRule ^(.*)$ /wordpress/index.php/$1 [L,E=RUN_CODE:eu]

NGINX – Server Block

	location ~* /eu/wordpress(.*) {
			if (!-f $request_filename) {
					set $code 'eu';
					rewrite ^(.*)$ /wordpress/index.php?$1 last;
					break;
			}
	}

In the WordPress root `index.php` this was added at the top of the file

	$pos = strpos($_SERVER['REQUEST_URI'], '/wordpress');
	if ($pos !== 0) {
		$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], $pos);
	}

Wordpress theme `functions.php`

	add_filter('post_link', 'link_mcnab');
	add_filter('page_link', 'link_mcnab');
	add_filter('bloginfo_url', 'link_mcnab');
	function link_mcnab($link)
	{
		if (isset($_SERVER['REDIRECT_RUN_CODE']) && $_SERVER['REDIRECT_RUN_CODE']) {
			$homeUrl = home_url();
			$domain = substr($homeUrl, 0, strrpos($homeUrl, '/'));
			$link = str_replace($domain, $domain . '/' . $_SERVER['REDIRECT_RUN_CODE'], $link);
		}

		return $link;
	}