Nginx正则表达式失败

时间:2014-09-08 00:25:06

标签: regex nginx

当我访问http://example.comhttp://example.com/index.html时,仍会转到handleURL.html

这就是我所拥有的

server {
    listen 80;
    listen [::]:80;

    root /var/www/vhosts/example.com/public;
    index index.html;

    server_name example.com www.example.com;

    access_log /var/log/nginx/example.com/access.log;
    error_log /var/log/nginx/example.com/error.log;

    rewrite "^/([a-z0-9]{4,8})$" /forward.php?shortcode=$1;
    rewrite "^/.{10,500}$" /handleURL.html;

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


    location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
}

如果网址的字符数在10,500之间,我想显示不同的html文件。

2 个答案:

答案 0 :(得分:0)

Nginx可能不在乎,但看起来正则表达式不应该在引号中。除非您在替换网址中使用输入的字符串,否则不需要捕获它,所以括号是不必要的。

如果要为每个字符串选择不同的文件,可以在替换字符串中使用捕获的字符串。例如rewrite "^/(.{10,500})$" /wiki/$1 last;会匹配example.com/agreatpage.html并将其转换为example.com/wiki/agreatepage.html

简单地根据rewrite "^/.{10,500}$" /Redirect.html last;之类的长度重定向到另一个页面

参考文献: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

修改 在进一步阅读之后,如果正则表达式用双引号括起来,nginx就可以了,如果表达式包含{或},则必须这样做,否则解析器会将这些错误解释为打开一个块并关闭一个块。

<强> EDIT2: 我目前唯一看到的问题是:

rewrite "^/([a-z0-9]{4,8})$" /forward.php?shortcode=$1;
rewrite "^/.{10,500}$" /handleURL.html;

据我所知,应该是:

rewrite "^/([a-z0-9]{4,8})$" /forward.php?shortcode=$1 last;
rewrite "^/.{10,500}$" /handleURL.html last;

答案 1 :(得分:0)

我可以解决此问题的唯一方法是删除所有重写并添加index.php并将所有内容传递给index.php我最终得到了以下配置。

server {
        listen 80;
        listen [::]:80;

        root /var/www/vhosts/example.com/public;
        index index.php index.html;

        server_name example.com www.example.com;

        log_format compression '$host - $remote_addr - $remote_user [$time_local] '
                           '"$request" $status $body_bytes_sent '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';

        access_log /var/log/nginx/example.com/access.log compression;
        error_log /var/log/nginx/example.com/error.log;

        location / {
                try_files $uri $uri/ /index.php?$query_string;
        }       

        location ~ \.php$ {
                try_files $uri /index.php =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}

谢谢你们!