I have several subdomain based sites in my CMS like:
a.site.com
b.site.com
All uploaded files are under the /upload
directory like:
site.com/upload/2012/a.jpg
But URL's are generated like this: "/upload/2012/a.jpg
". In this situation, the same image can be accessed at a.site.com/upload/2012/a.jpg
URL and b.site.com/upload/2012/a.jpg
URL.
How can I configure nginx to redirect all requests that point to /upload
to site.com/upload
. Example:
a.site.com/upload/2012/a.jpg => site.com/upload/2012/a.jpg
adding the following to the config for your subdomains should do the trick if you have a sepperate server block for *.site.com
location /upload/ {
rewrite ^ http://site.com$request_uri permanent;
}
if you're catching both site.com and *.site.com in the same server block you need to add an extra if statement to that:
location /upload/ {
if( $host != site.com ) {
rewrite ^ http://site.com$request_uri permanent;
}
# if we get here it's the main site
# directives for serving http://site.com/upload/ go here
}
Nginx not generate urls. It is a web server. It answer to requests like http://site.com/upload/2012/a.jpg
.
So you can change relative links /upload/2012/a.jpg
in you html code to absolute http://site.com/upload/2012/a.jpg
and not change nginx config. Or change nginx config for subdomains and nginx will send same image for http://site.com/upload/2012/a.jpg
and http://a.site.com/upload/2012/a.jpg
and http://b.site.com/upload/2012/a.jpg
requests.
If you prefer change config you have to create unificated config for all subdomains. Because
When searching for a virtual server by name, if name matches more than one of the specified variants, e.g. both wildcard name and regular expression match, the first matching variant will be chosen, in the following order of precedence
server {
listen 80;
server_name *.site.com;
location ^~ /upload {
root /real/path/to/upload/;
...
}
}
location directive manual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With