简体   繁体   English

用PHP和MySQL和htaccess重写URL

[英]URL rewrite with PHP & MySQL and htaccess

I have my site as localhost/tutorials/rewrite/news.php on this page are titles from news articles that are in my database. 我在此页面上将我的站点localhost/tutorials/rewrite/news.phplocalhost/tutorials/rewrite/news.php ,这些都是来自数据库中新闻文章的标题。 Each title is a link to read the article. 每个标题都是阅读文章的链接。 The link is 链接是

'<a href="read-news.php?url=' . $url . '">' . $title1. '</a>'

The read-news.php page gets the url and uses it in an sql statement to get the article from the database read-news.php页面获取URL并在sql语句中使用它以从数据库获取文章

$url = $_GET['url'];
$sql = "SELECT * FROM news WHERE url = '$url'";

My link on the news.php page and the url on the read-news.php looks like this 我在news.php页面上的链接和read-news.php上的URL看起来像这样

localhost/tutorials/rewrite/read-news.php?url=the-news-today

How can i get it to look like 我怎样才能看起来像

localhost/tutorials/rewrite/read-news/the-news-today.php

I have used the following htaccess code which by looking at other examples i thought should be enough to fix it 我使用了以下htaccess代码,通过查看其他示例,我认为该代码足以解决它

RewriteRule ^read-news/(.*).php /read-news.php?url=$1 [PT]

Any help please 任何帮助请

Do it how Wordpress does it. 做到Wordpress如何做到这一点。 Rewrite everything into index.php and parse the url from script. 将所有内容重写为index.php并从脚本解析URL。

edit: your RewriteRule needs some work too. 编辑:您的RewriteRule也需要一些工作。 try this: 尝试这个:

RewriteRule ^read-news/(.*)\\.php$ /read-news.php?url=$1 [PT]

(you need to use a "$" to signal the end of your rewrite and escape the . before "php" with a backslash) (您需要使用“ $”来表示重写已结束,并在“ php”前使用反斜杠转义。)

Also, you should link to your pages how you want them displayed: 另外,您应该将页面链接到您希望它们如何显示:

href="localhost/tutorials/rewrite/read-news/the-news-today.php"

The .htaccess won't magically change the urls for you. .htaccess不会神奇地为您更改网址。

Also if you want to be able to access your query string variables, i would add QSA to your flags: [PT,QSA] 另外,如果您希望能够访问查询字符串变量,我会在您的标志中添加QSA: [PT,QSA]

that way you can still access your url variable with $_GET['url'] . 这样,您仍然可以使用$_GET['url']访问url变量。

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

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