Art
Art

Reputation: 848

setting up rewrite rules in nginx for location rewrites

I am a total noob to nginx. I am trying to set up some rules in nginx for location rewrites. What I am trying to achieve is this:

1. no change
https://hello.domain.com/index.php --> https://hello.domain.com/index.php

2. subdomain needs to be included
https://hello.domain.com --> https://hello.domain.com/index.php?sub=hello

3. subdomain & folder structure needs to be included
https://hello.domain.com/dir1/15 --> https://hello.domain.com/index.php?sub=hello&path=dir1/15

4. requests to certain directories ( images, css, etc... ) need to be ignored
https://hello.domain.com/images/logo.png --> https://hello.domain.com/images/logo.png

I am able to get the subdomain into a variable $sub with this

server_name ~^(?<sub>.+)\.domain\.com$;

I tried to use the location directive but it only works for #2 and #3 in the list

location / {
        rewrite ^ /index.php?sub=$sub&path=$request_uri;
    }

Any help would be greatly appreciated!!!

Upvotes: 0

Views: 365

Answers (1)

Midgard
Midgard

Reputation: 402

This might help you forward:

server_name ~^(?<sub>.+)\.domain\.com$;

location /images {
    # You can put this code in a snippet file and than include
    # it with e.g. `include assets.conf;` so you can use more
    # folders with longest prefix match blocks, which are more
    # efficient than regex blocks.

    # Tell the browser to cache this for one day
    expires 1d;

    # Just give the resource
    try_files $uri =404;
}

location /index.php {
    # PHP stuff goes here
}

location / {
    rewrite ^ /index.php?sub=$sub&path=$uri last;
}

Upvotes: 1

Related Questions