如何重写这样的网址?重写、网址

2023-09-02 01:10:58 作者:别用吻过她的嘴说爱我

我将如何改写(在我的博客每个帖子):

 的http://localhost/post.php ID = 13

至

HTTP://本地主机/本,是最冠军的最后/ 13
 

和(无ID)

 的http://localhost/post.php ID = 13

至

HTTP://本地主机/本,是最冠军的最后/
 

解决方案

试试这个规则:

  RewriteEngine叙述上
重写规则^ [^ /] + /( d +)$ post.php中?ID = $ 1
 
Nginx Rewrite重写模块

这将改写请求的URI路径像 /这-是最冠军的最后/ 13 内部以 /后.PHP ID = 13 ?;所以它是相当的另一种方式圆你描述的。但是,这是如何工作的mod_rewrite:你只能改变传入的请求,而不是传出响应

现在,如果你想省略的数字ID,你的标题必须是新的ID:

 重写规则^这 - 是最冠军的最后/(13)?$ post.php中?ID = 13
 

这意味着它需要是唯一的。否则的标题不能明确映射到数字ID。在这种情况下,冠军肯定会更容易,如果你通过了标题的 post.php中的:

 的RewriteCond%{REQUEST_FILENAEM}!-f
重写规则^([^ /] +)/ $ post.php中?标题= $ 1
 

显然,由于标题是独一无二的,你不需要数字ID了。

How would I rewrite ( for every posts in my blog ):

http://localhost/post.php?id=13

to

http://localhost/this-is-the-title-of-the-post/13

AND ( without id )

http://localhost/post.php?id=13

to

http://localhost/this-is-the-title-of-the-post/

解决方案

Try this rule:

RewriteEngine on
RewriteRule ^[^/]+/(d+)$ post.php?id=$1

This will rewrite a requested URI path like /this-is-the-title-of-the-post/13 internally to /post.php?id=13; so it’s rather the other way round of what you described. But that’s how mod_rewrite works: You can only change incoming requests and not outgoing responses.

Now if you want to omit the numeric ID, your title needs to be the new ID:

RewriteRule ^this-is-the-title-of-the-post/(13)?$ post.php?id=13

That means it needs to be unique. Otherwise the title cannot be mapped onto the numeric ID unambiguously. In that case the title it would certainly be easier if you pass the title to post.php:

RewriteCond %{REQUEST_FILENAEM} !-f
RewriteRule ^([^/]+)/$ post.php?title=$1

Obviously, since the title is unique, you don’t need the numeric ID any more.