Working Subdirectory Multisite Nginx rules

I have tried to use multiple different configurations but I just can’t have working multisite in subdirectory. It always forces subdomains or can’t find the sites and I’ll get 502.

Anyone struggling with this use this in your nginx configuration:

\# Rewrite multisite '.../wp-.*' and '.../*.php'.
if (!-e $request_filename) {
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) /wp$1 last;
    rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ /wp$1 last;
}

Then you can access all sites like this:

example.com/wp-admin/
example.com/site1/wp-admin/
example.com/site2/wp-admin/
example.com/site1/wp-admin/edit.php
example.com/site2/wp-admin/edit.php

Credits: wp-skeleton

4 Likes

Sometimes you would want to have subdirectory multisite inside subdirectory.
Like:

example.com/demo (main-site)
example.com/demo/site1
example.com/demo/site2/wp-admin/edit.php

To achieve this place your web folder inside htdocs/demo/

# Rewrite everything under /demo folder
if (!-e $request_filename) {
  #Main wordpress site
  rewrite /wp-admin$ $scheme://$host$uri/ permanent;
  rewrite ^/demo/(wp-.*.php)$ /demo/wp/$1 last;
  rewrite ^/demo/(wp-(content|admin|includes).*) /demo/wp/$1 last;

  #Add subdirectory multisite rules eg. example.com/demo/site1/wp-admin
  rewrite ^/demo/[_0-9a-zA-Z-]+(/wp-.*) /demo/wp$1 last;
  rewrite ^/demo/[_0-9a-zA-Z-]+(/.*\.php)$ /demo/wp$1 last;
}

No guarantees but It works for me :wink:

Thank you for this helpful thread!

I have a problem with my configuration: I have WPML installed as network plugin. When I click on “WPML” in the admin menu of a site, I get the error:
502 Bad Gateway

The URL I call:
http://mydomain.dev/mysite/wp-admin/admin.php?page=sitepress-multilingual-cms/menu/languages.php

My nginx configuration:

server {
  
  (... trellis default ...)

  # See Virtualbox section at http://wiki.nginx.org/Pitfalls
  sendfile off;
  rewrite ^/(wp-.*.php)$ /wp/$1 last;
      rewrite ^/(wp-(content|admin|includes).*) /wp/$1 last;
  add_header Fastcgi-Cache $upstream_cache_status;

  # Rewrite multisite '.../wp-.*' and '.../*.php'.
  if (!-e $request_filename) {
      rewrite /wp-admin$ $scheme://$host$uri/ permanent;
      rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) /wp$1 last;
      rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ /wp$1 last;
  }
  
  include includes.d/mydomain.de/*.conf;
  include wordpress.conf;

  location ~ \.php$ {
    try_files $uri =404;
    error_page 404 /index.php;

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
    fastcgi_pass unix:/var/run/php-fpm-wordpress.sock;
  }
}

What am I doing wrong? Is there something missing? Another plugin (https://de.wordpress.org/plugins/ns-cloner-site-copier/) had the same 502 error on URL
http://mydomain.dev/wp-admin/network/admin.php?whatever=parameters&another=one

Thank you!