【问题标题】:Rewrite URL with NGINX用 NGINX 重写 URL
【发布时间】:2016-02-07 20:08:48
【问题描述】:

我有一个用 php 编码的博客,里面有几篇文章,但要阅读一篇文章,url 应该像http://myblog/post.php?url=an-article-tilte&id=7

我想用一种最聪明的方式来访问带有 URL 的文章(并改进引用)。在我的数据库中,每篇文章都有一个url 属性,其标题为“kebab-case”(例如,“欢迎来到我的博客”将是“欢迎来到我的博客”)。

总而言之,要访问“欢迎来到我的博客”帖子(id 等于 7),我会输入 http://myblog.com/post/welcome-to-my-blog-7 而不是 http://myblog.com/post.php?url=welcome-to-my-blog&id=7

在我的博客 nginx 配置文件中我有这个:

server {
    listen   80;
    root /opt/http/nginx/sites/myblog/www;
    index index.php index.html;
    server_name myblog.com www.myblog.com;

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

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 365d;
    }

    location ~*  \.(pdf)$ {
        expires 30d;
    }

    client_max_body_size 3M;

    error_page 403 /index.php;

    # pass the PHP scripts to FastCGI server listening on /var/run/php5-fpm.sock
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    gzip on;
    gzip_min_length  1100;
    gzip_buffers  4 32k;
    gzip_types    text/plain application/x-javascript text/xml text/css;
    gzip_vary on;

    access_log   /var/log/nginx/www.myblog.access.log;
    error_log   /var/log/nginx/www.myblog.error.log;
}

我想我必须放入这样的东西,但是当我尝试重新启动 nginx 时它会出错。所以我不知道它有什么问题。

location @rewrites {
    if ($uri ~* ^/post/([a-zA-Z0-0\-]+)-([0-9]+)) {
        rewrite ^/post.php?url=$1&id=$2;
    }
}

使用 apache 很简单,但是有没有办法在 nginx 上重现它?

【问题讨论】:

    标签: php regex nginx url-rewriting server


    【解决方案1】:

    我认为问题是缺少美元 $ 来关闭正则表达式字符串,您可以按照以下方式重写您的规则:

    location /post/ {
        rewrite ^/post/([\w-]+)-(\d+)$ /post.php?url=$1&id=$2;
    }
    

    地点:

    • \w 等价于 [a-zA-Z0-9_] (如果你喜欢删除 unescore _ 在扩展版本中重写它)
    • \d[0-9]

    注意:如果您使用 ~*,则它是不区分大小写的匹配(不需要双精度 A-Za-z)。

    更新:如果我理解正确你需要什么,我们必须重写规则以做相反的事情(向post.php?url={kebab-title}&id={id-number}提出请求并实际获取``post/{烤肉串标题}-{id-number}

    location ~ ^/post\.php\?url=(.*)&id=(\d*)$ {
        alias /post/$1-$2;
    }
    

    更新 2 为避免在/post/ 下出现不必要的匹配,您还可以使用此替代(更具体)版本:

    location ~ ^/post/((?:\w+-)+\w+)-(\d+)$ {
        rewrite /post.php?url=$1&id=$2;
    }
    

    【讨论】:

    • 我赞成您的回答,因为这正是我正在寻找的想法!现在,我在链接 http://myblog.com/post/an-example-article-8 上有一个 404。但我相信我们会解决这个问题的!
    • @MaximeLafarie:尝试更新中提出的解决方案,我认为这是您需要的。
    • 很抱歉,您的第一个答案很有效!我忘记了我的博客位于“博客”目录中,然后我不得不在代码中的所有“/”之前添加“/博客”来调整您的答案。我到处都做过,但我忘了在这里做:/post.php?url=$1&id=$2;。感谢您的回答,这正是我想要的,感谢您,我现在了解了 nginx url 重写的工作原理。
    • a little trick 避免 404 错误,一切正常!谢谢!编码也愉快!
    • @MaximeLafarie:如果你想尝试另一种方法(从长远来看不那么晦涩),我认为最后一次改进的更新必须避免不必要的匹配。
    猜你喜欢
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多