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:

Credits: wp-skeleton


Sometimes you would want to have subdirectory multisite inside subdirectory.
Like: (main-site)

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.
  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:

My nginx configuration:

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

  # See Virtualbox section at
  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/*.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 ( had the same 502 error on URL

Thank you!