在nginx中添加过期标头

时间:2013-11-27 08:21:52

标签: apache nginx

过去很容易用apache mod_headers设置标头过期,但我很难找出在nginx confi文件中添加它的位置。 这是我的nginx.conf:

#user  nginx;
worker_processes  1;

#error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

#pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    #tcp_nodelay        on;
    tcp_nodelay        on;

    gzip  on;
    gzip_http_version 1.1;
    #gzip_http_version 1.0;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_proxied any;
    gzip_types text/plain text/html text/css application/x-javascript text/xml;
    #gzip_min_length  1100;
    gzip_buffers 16 8k;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    server_tokens off;

    include /etc/nginx/conf.d/*.conf;

}

我应该在哪里添加标题到期部分,如

location ~* \.(js|css)$ {
  expires 30d;
}

我尝试将其添加到“http”内或包含在另一个块“server”中,但它会生成错误,如未知指令“server”或“location”。

2 个答案:

答案 0 :(得分:4)

在nginx中添加expires头很容易。您需要将位置块放在服务器块中。 /your/nginx_dir/sites-enabled/中必须有默认文件。 如果是,您可以直接编辑它并在其中添加您的位置块,或者您可以在nginx.conf的http块内复制默认文件的全部内容。

如果您选择编辑默认文件,请不要忘记在nginx.conf中添加这样的行

include /etc/nginx/sites-enabled/*;

如果找不到默认文件,只需编辑你的nginx.conf就可以看到这样了

#....
server_tokens off;
#up to here the conf is the same as yours

#edit starts here, just add this server block
server {
    #default_server is not necessary but is useful if you have many servers 
    #and want to capture requests where the host header doesn't match any server name
    listen       80 default_server;
    #requests with host header that matches server name will be handled by this server
    server_name  your.domain.com localhost; 

    #change your document root accordingly
    root /path/to/your/html/root; 

    #you can have as many location blocks as you need
    location ~* \.(js|css)$ {
        expires 30d;
    }
}
#end of conf changes

include /etc/nginx/conf.d/*.conf;

由于您来自apache,只需将nginx的服务器视为apache的VirtualHost。不要忘记在conf文件中的每次更改后重新加载nginx

答案 1 :(得分:0)

/etc/nginx/conf.d/内查看您可能会找到一个名为default的文件,然后您会在此处找到location /