如果目录不存在,则查找文件nginx

时间:2015-03-28 05:19:55

标签: apache .htaccess nginx url-rewriting

我正在将旧网站从运行apache的框移动到运行nginx的新框。旧网站使用.htaccess规则,我发现很难将其转换为nginx配置语法。

具体而言,如果旧网站上的请求是example.com/video,那么,如果没有目录video,则会加载video.phpvideo.html文件。< / p>

以下是.htaccess规则:

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.html [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule .? /index.html [L]

我在nginx中尝试了以下操作而没有运气(404):

server {
        listen       80;
        server_name  example.org www.example.org;

        access_log /var/log/example.org/access.log;
        error_log /var/log/example.org/error.log;

        root   /var/www/vhosts/example.org/;

        index  index.html index.htm;

        location / {

                rewrite ^(.*)$ /$1\.php break;
                rewrite ^(.*)$ /$1\.html break;
                if (!-e $request_filename){
                        rewrite .? /index.html break;
                }
        }
        location /app {
                rewrite ^/app/? /join?p=getApp redirect;
        }
}

1 个答案:

答案 0 :(得分:1)

try_files指令仅适用于此场景:

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

您的nginx配置将如此:

server {
    listen       80;
    server_name  example.org www.example.org;

    access_log /var/log/example.org/access.log;
    error_log /var/log/example.org/error.log;

    root   /var/www/vhosts/example.org/;

    index  index.html index.htm;

    location / {
        try_files $uri $uri.php $uri.html;
    }

    location /app {
            rewrite ^/app/? /join?p=getApp redirect;
    }