简体   繁体   English

用.htaccess重写URL?

[英]Rewriting urls with .htaccess?

I'm trying to rewrite a url but I can't seem to make it happen. 我正在尝试重写url,但似乎无法实现。

I just want one working example so I can move on to all pages of my website. 我只需要一个可行的示例,这样我就可以继续浏览网站的所有页面。

So I have this link: 所以我有这个链接:

www.domain.com/article.php?id=1

And I can to change it to: 我可以将其更改为:

www.domain.com/article/1/

That's ok for now, later I'll replace the number with the article title. 现在可以,以后我将其替换为文章标题。

This is what I have on my .htaccess file: 这是我的.htaccess文件上的内容:

RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^article\.php\?id=([0-9]+)$    article/$1/

What is wrong it it? 怎么了 I heard that the .htaccess file needs to be in ASCII if using FTP to save in on the server but I don't know how to do it since I created it by myself. 我听说如果使用FTP将.htaccess文件保存在服务器上,则该文件必须为ASCII格式,但是由于我自己创建了该文件,因此我不知道该怎么做。

You can't match against the query string in a rewrite rule, you need to match against %{QUERY_STRING} in a condition: 您无法在重写规则中与查询字符串匹配,而在以下情况下需要与%{QUERY_STRING}匹配:

RewriteEngine On    # Turn on the rewriting engine
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteRule    ^article\.php$    article/%1/? [L]

This internally rewrites your request to /article/1/ . 这会在内部将您的请求重写为/article/1/ The browser will still see the old URL. 浏览器仍然会看到旧的URL。

What you are more likely looking for is to match against the request: 您最有可能寻找的是与请求匹配:

RewriteEngine On
RewriteCond %{THE_REQUEST} \ /+article\.php\?id=([0-9]+)
RewriteRule ^ /article/%1/? [L,R=301]

RewriteRule ^article/([0-9]+)/?$ /article.php?id=$1 [L,QSA]

从字面上看,您正在反向执行此操作。

RewriteRule ^article/([0-9]+)$ /article.php?id=$1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM