Milo
Milo

Reputation: 307

How can I automate this nginx rewrite rule?

I'm afraid I'm in way over my head. I'm sure I'm missing something simple, but it's not clicking together so far. Any help would be greatly appreciated.

I've got a domain that hosts a number of micro sites, structured like so:

I'm converting over from Apache to Nginx. When I was using Apache, this is the set of rewrite rules that worked for as many folders as I wanted.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1#%{REQUEST_URI} ([^#]*)#(.*)\1$
RewriteRule ^(.*)$ %2index.php [QSA,L]

At this point, I am able to get the sites working using individual rules. But it's not really a feasible solution for my circumstance.

location /site1 {
    try_files $uri $uri/ /site1/index.php?$args;
}
location /site2 {
    try_files $uri $uri/ /site2/index.php?$args;
}
location /site3 {
    try_files $uri $uri/ /site3/index.php?$args;
}

There's gotta be a better way. I'm just such a noobie with Nginx, I can't quite figure it out. Thanks in advance for your help.

Upvotes: 0

Views: 227

Answers (3)

Milo
Milo

Reputation: 307

I finally found a solution here: https://github.com/rtCamp/easyengine/issues/31

set $dir "";
if ($request_uri ~ ^/([^/]*)/.*$ ) {
  set $dir1 /$1;
}
location / {
  try_files $uri $uri/  $dir1/index.php?$args;
}

Upvotes: 1

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42899

After reading a reply on my first answer I've changed it to this, don't know if you'll need the $suburi but it's there just in case.

server {
  server_name example.com;
  index index.php; # need this
  location / {
    try_files $uri $uri/ /index.php;
  }
  location ^~ (?<subfolder>/[^/]+)(?<suburi>.+) {
    try_files $uri $uri/ $subfolder/index.php$is_args$query_string;
  }
}

Alternative with no named capture blocks

  location ^~ (/[^/]+)(.+) {
    try_files $uri $uri/ $1/index.php$is_args$query_string;
  }

Upvotes: 1

Astery
Astery

Reputation: 1256

I think about something like these:

location ~ ^/(.*)/*.*$ {
    try_files $uri $uri/ /$1/index.php?$args;
}

Upvotes: 0

Related Questions