Nginx配置

时间:2012-03-05 02:35:10

标签: php configuration nginx

我正在查看几个文档,但出于某种原因,我无法理解我正在尝试做的所需的配置。基本上我想要:

  • 所有目录请求都应保留其网址,但应由index.php处理

  • 应该在没有php处理的情况下提供各自目录(/ js /,/ css /和/ images /)中的所有.js,.css,.jpeg和.png文件。

  • 应拒绝所有其他文件访问(包括所有.php)。

我已经尝试为.php处理设置位置,但我永远无法弄清楚如何让它正常工作。我会坚持下去,但希望得到一些快速帮助:)

谢谢!

编辑2:我想我想出了一些体面的东西。它可能不完美,但应该有效。

server {
    listen 80;

    server_name _;
    server_tokens off;

    root /mypath/www;

    access_log /mypath/access.log;
    error_log /mypath/error.log;

    index index.html;

    location ^~ /app {
        return 404;
    }

    location ~ \.conf {
        return 404;
    }

    location ~ \.php {
        return 404 ;
    }

    location ~ /images/.*.(jpg|jpeg|png|gif) {
        try_files $uri $uri = 404;
        expires max;
    }

    location ~ /css/.*.css {
        try_files $uri $uri = 404;
        expires 1d;
    }

    location ~ /js/.*.js {
        try_files $uri $uri = 404;
        expires 1d;
    }

    location / {
        try_files $uri @PHPProxy;
        error_page 500 501 502 503 504 505 $document_root/error.html;
    }

    location @PHPProxy {
        include fastcgi_params;
        fastcgi_pass unix:/tmp/php.socket;
        fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    }
}

1 个答案:

答案 0 :(得分:2)

这是一种有趣的想法。我以前只是确保阻止目录或确保我没有任何我不希望在我的doc根目录中访问的文件。

我想我找到了办法。它实际上不会为其他文件提供404或403,它只是将除指定目录之外的所有内容重写为/index.php。

这是我测试过的配置:

server {
listen 80;
listen your.domain.name:80;
server_name your.domain.name;

root /var/www/vhost/testing;
server_tokens off;

location ~ ^/(images|css|js)/.* {
    expires max;
}
location / {
    index index.php;
    rewrite ^(.*)$ /index.php$1 last;
}
location ~ ^/index.php {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param PATH_INFO $fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
}
}

因此,/ images,/ css或/ js中的任何内容都会加载,但其他所有内容都会被重写到索引文件中。

请记住,任何不在这3个文件夹中的文件都会被完全忽略。

相关问题