Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx - serve only images

Tags:

nginx

I'm trying to setup nginx so "static.domain.com" can only serve images. This is what I have come up with, but I know it can be done more efficiently. I want to serve 403.html if someone tries to access any .htm, .php, directory (anything else I'm missing?) files. Of course, with the exception of 403.htm and static.htm files.

Any ideas how I can secure this properly?

server {
     listen          xx.xx.xx.xx:80;

     server_name     static.domain.com;

     root            /www/domain.com/httpdocs;
     index           static.htm;

     access_log      off;
     error_log       /dev/null crit;

     error_page  403  /403.html;

     # Disable access to .htaccess or any other hidden file
     location ~ /\.ht  {
        deny all;
     }

     location ~* \.php {
        deny all;
     }

     # Serve static files directly from nginx
     location ~* \.(jpg|jpeg|gif|png|bmp|ico|pdf|flv|swf|exe|html|htm|txt|css|js) {
        add_header        Cache-Control public;
        add_header        Cache-Control must-revalidate;
        expires           7d;
     }
}
like image 557
Brian Smith Avatar asked Apr 25 '12 04:04

Brian Smith


People also ask

Does Nginx serve static files?

Configure NGINX and NGINX Plus to serve static content, with type-specific root directories, checks for file existence, and performance optimizations.

What is Try_files in nginx?

The try_file directive is in the server and location blocks and specifies the files and directories in which Nginx should check for files if the request to the specified location is received. A typical try_files directive syntax is as: location / { try_files $uri $uri/ /default/index.html; }

How do I use nginx as a file server?

Serving static files using nginx as web server is a good option. For making the static files available you need to copy your testfolder to /usr/share/nginx/html inside the nginx image. After which you will be able to see the files on your browser on port 8080.


1 Answers

Why not move the images up and then deny all?

location ~* \.(jpg|jpeg|gif|png|bmp|ico|pdf|flv|swf|exe|html|htm|txt|css|js) {
   add_header        Cache-Control public;
   add_header        Cache-Control must-revalidate;
   expires           7d;
}
location  / {
    deny all; 
}

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else. -From http://wiki.nginx.org/HttpCoreModule#location

Edit: Removed "=" from "location /" To quote the docs:

location  = / {
  # matches the query / *only.* 
}
location  / {
  # matches *any query*, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
}

My bad.

like image 195
Andrew T Avatar answered Sep 18 '22 09:09

Andrew T