My goal is to serve requests from mobile devices on a different URL (a specific location) than the generic one, used for desktop version of my website.
I also need to serve files from a different document root, which should be seen as the base path (I don't want my location to be part of the directory structure).
I have this config (extract):
location / {
if ($http_user_agent ~* '(iPhone|iPod|iPad|Android|BlackBerry|webOS|Windows Phone)') {
rewrite ^ /mobile/ permanent;
}
index index.html index.htm;
}
location /mobile/ {
root /my/mobile/website; # new document root
rewrite ^/mobile(.*)$ $1 break; # strip /mobile prefix from the path
# try_files $uri $uri/ /index.html; # I tried this (don't know exactly what this should do), but it doesn't work anyway
index index.html index.htm;
}
This doesn't work and is causing a redirection loop.
It seems that requests to www.mydomain.com/mobile/
aren't matched from the location /mobile/
section but still fall into location /
, causing a 301 redirect loop.
If I leave the rewrite ^/mobile(.*)$ $1 break;
directive away it works, I get an index.html page that I placed into /my/mobile/website/mobile
directory for testing, but that's not where my files should be served from.
What am I missing?
I am guessing that the problem is
index
./mobile/
.rewrite...break
changes the URL to/
but remains inside the samelocation
block to continue processing the request.index
directive changes the URL to/index.html
then searches for a matchinglocation
which moves to the otherlocation
block, resulting in a redirection loop.You could consider using
alias
to replace bothroot
andrewrite...break
.For example:
Note that the
location
andalias
statements should both end with/
or neither end with/
for correct alias operation.