【发布时间】: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