开发者

How to configure nginx, let some sub-domains can only visit js/css files?

I have a website(for example: test.com), which has 2 kinds of subdomains:

  1. test.com
  2. 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=$ver开发者_如何学Pythonsion 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.

server {
  server_name static.test.com;
  root /var/www/static;
  location / {
    rewrite ^/([^\/]+\.css)$ /css/$1 break;
    rewrite ^/([^\/]+\.js)$ /js/$1 break;
    rewrite ^/([^\/]+\.(png|jpg|jpeg))$ /images/$1 break;
  }
}

For the second question

Yes, your cofig is correct. But you should use permanent redirect or nginx will redirect request with 302 Moved Temporarily. Also listen 80 is 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.

server {
    server_name ~^static_(.*)\.test\.com$;
    set $version $1;
    rewrite ^/public/(.*) http://test.com/public/$1?v=$version permanent;
    return 404;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜