I have a website(for example: test.com), which has 2 kinds of subdomains:
- test.com
- static_${version}.test.com
The 1st one is the main subdomain, and the 2nd one is only used for static files(js/css/image). The ${version} is a version number, it is changed when there is new version of js/css/images files, I need it because the client may cache the old ones.
Now I use nginx, but I don’t configure it about subdomains, just simply rewrite all subdomains to the main test.com domain.
It works, but one day I found a search engine, use the static.test.com as the main domain to visit my site.
How do I configure the nginx, to let the static.test.com can only visit static files, while the main domain can visit all?
UPDATE
I hope request of static.test.com with js/css/images will rewrite to test.com, not to a static file in disk. And other requests(not js/css/images) will return 404 directly.
Thanks for Timofey Stolbov’s answer, I write a config now:
server {
listen 80;
server_name ~^static_(.*)\.test\.com$;
set $version $1;
rewrite ^/public/(.*) http://test.com/public/$1?v=$version last;
return 404;
}
Since my js/css/images files are all in “public” directory, so I just check if it starts with “public”. If not, just return 404.
But I don’t know is it correct, especially the return 404, or is there any better way to do this.
I use something like this.
For the second question
Yes, your cofig is correct. But you should use permanent redirect or nginx will redirect request with
302 Moved Temporarily. Alsolisten 80is implied by default.I don’t think that using redirect for every js/css/image is good idea, so think twice. 🙂
And here is config.