Nginx – rewrite or internal redirection cycle while internally redirecting error on Nginx

nginxrewrite

I just migrate from Apache to Nginx and trying to set up rewrite rules. I have a virtual host and this is the structure of virtual host

/var/www/name-of-virtual-host/
├── wp1
│   ├── wp-admin
│   ├── wp-content
│   └── wp-includes
└── wp2
    ├── wp-admin
    ├── wp-content
    └── wp-includes

As you see I have 2 different WordPress installations in different folders.
So I'm trying to create a rewrite rule to work with these 2 WPs.

This is my location definition:

        location / {
                try_files @missing $uri;
        }
        location @missing {
                rewrite ^/([a-z-])(/.*)$ /$1/index.php last;
        }
        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

                # With php5-cgi alone:
                #fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }

If URI is /wp1/permalink-of-post/ it should use /wp1/index.php and if /wp2/permalink-of-post/ it should use /wp2/index.php .

But I'm getting rewrite or internal redirection cycle while internally redirecting to error.

How can I write my rewrite rules to use with multiple WP installations ?

UPDATE 1

An example WordPress .htaccess file:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wp1/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wp1/index.php [L]
</IfModule>

# END WordPress

Best Answer

Isn't your try_files in the wrong order? Perhaps that's what causing you the headache and the endless cycles, because the file @missing, well, is indeed missing from your filesystem, and redirecting back to $uri indeed must cause an endless cycle for sure?

-try_files @missing $uri;
+try_files $uri @missing;

Nonetheless, if you only have two WordPress sites, I think a better approach might be to simply have a little bit of copy-paste going on, instead of trying to invoke regular expressions and all each time.

E.g., would probably be better to have the following than trying to do lots of rewriting and multiple redirects:

location /wp1 {
    try_files $uri /wp1/index.php;
}
location /wp2 {
    try_files $uri /wp2/index.php;
}