我有一个街机游戏网站。我想将我的网址转换为 sef。
category : example.com/index.php?category=mario-games > example.com/category/mario-games
game details : example.com/index.php?game=mario-game > example.com/mario-game.html
featured : example.com/featured.php > example.com/featured
pages : example.com/page.php?id=contact > example.com/page/contact
在搜索互联网后,我成功实现了重写规则。但我的旧网址仍然可以访问。我怎样才能将旧网址重定向并重写为新网址?
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
root /usr/share/nginx/domain;
index index.php index.html index.htm;
#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;
location / {
rewrite ^/(.*).html$ /index.php?game=$1 last;
}
location /category {
rewrite ^/(.+)/$ /$1 permanent;
rewrite ^/category/(.*)$ /index.php?category=$1 last;
}
location /page {
rewrite ^/(.+)/$ /$1 permanent;
rewrite ^/page/(.*)$ /page.php?id=$1 last;
}
location /featured {
rewrite ^/(.+)/$ /$1 permanent;
rewrite ^/(.*) /featured.php last;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location = /favicon.ico { log_not_found off; access_log off; }
location = /robots.txt { log_not_found off; access_log off; }
location ~* .(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
expires max; log_not_found off; access_log off;
}
location ~* \.(js|jpg|png|css)$ {
expires 30d;
}
}
答案1
我会在你的内部进行重定向index.php
,如下所示:
if (isset($_GET['category'])) {
header('HTTP/1.1 301 Moved Permanently');
header("Location: http://www.domain.com/category/" . $_GET['category']);
}
但是,它可以与 nginx 类似地工作(我自己还没有测试过这样的解决方案):
location = /index.php {
if ($arg_category ~ (.+)) {
return 301 http://www.domain.com/category/$1;
}
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
因此,我们匹配 PHP 文件,然后测试查询参数,将其捕获到正则表达式中以供指令使用return
。
答案2
您不能同时做这两件事。重写的目的是让您能够接受来自不同路径的请求。重定向的目的是将这些请求转移到您希望它们去的地方,包括对客户端的响应,使其始终转到那里(响应代码 301)。尝试同时做这两件事可能没有意义,也是不可能的,因为一旦完成一件事,客户端就已经在其他地方了。