3

Using the http://wiki.nginx.org/NginxHttpCoreModule#alias example regarding how to use sub directory aliases, I've noticed it does not mention how to do it dynamically.

In the following example...

location ~ ^/download/(.*)$ {
  alias /home/website/files/$1;
}

...the request "/download/book.pdf" will return the file "/home/website/files/book.pdf". Note again that only part of the request URI after the location is appended to the path defined by alias.

If I'm creating a folder labeled the username that the user created once signing up, then this folder name would always be unique and different. How do I alter the regex in the example above so that the word download also becomes a wild card sub directory?

location ~ ^/randomusername/(.*)$ {
  alias /home/website/profiles/randomusername/$1;
}

2 Answers 2

2

You need a little background about regex.

Please try the code below and see if it helps.

location ~ ^/([^/]+)/([^/?]+)$ {
  alias /home/website/profiles/$1/$2;
}
0
1

Well, after learning NGINX here is the answer I was looking for 9 years ago.

location / {

  # example rewrite rules for www.example1.com

  rewrite ^/get/users/?$ /getData.php?usersFilter=all                             last;
  rewrite ^/get/users/(\d+)/?$ /getData.php?userId=$1                             last;
  rewrite ^/get/users/(\d+)/comments/?$ /getData.php?userId=$1&commentsFilter=all last;

}

@Kristi Jorjii: Below, we use the /[^/]*$/ regex to match the part of the URL after the last slash.

rewrite ^/sitemap/[^/]*$ /var/www/html/sitemap/$1 last;
1
  • Amazing such a comeback. Now you can solve my problem as well: How to redirect all calls going to /sitemap(.*) to static files located at /var/www/html/sitemap$1 Apr 14, 2022 at 14:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .