使用.htaccess重写PHP URL

时间:2019-12-17 13:34:45

标签: .htaccess mod-rewrite url-rewriting

我有一个

形式的URL

motors.com/project?id=1&title=british-car-auctions

并希望将其更改为

motors.com/project/1/british-car-auctions

我使用了URL rewriting with PHPRewritting URL by htaccess的解决方案,但没有运气。至于URL的title部分,我正在用数据库中的破折号来称呼这个确切的文本,这应该不是问题。这个问题有任何可能的解决方案吗?

# mode_rewrite starts here

RewriteEngine on

# does apply existing directories, meaning that if the foilder exists 

RewriteCond %{REQUESTED_FILENAME} !-d

# check for file in directory with .hmtl extension

RewriteCond %{REQUEST_FILENAME}\.php -f

# here we actually show the page that has the .html extension

RewriteRule ^(.*)$ $1.php [NC,L]

#-----------------------------------------------------

RewriteCond %{REQUESTED_FILENAME} !-d

# check for file in directory with .hmtl extension

RewriteCond %{REQUEST_FILENAME}\.html -f

# here we actually show the page that has the .html extension

RewriteRule ^(.*)$ $1.html [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^news/([0-9]+)(/?)$/([0-9a-zA-Z\s_]+) news/article.php?id=$1&title=$2 [NC,L]

1 个答案:

答案 0 :(得分:0)

最终找到了解决方案。网址重命名与.php文件名不同。

所以代替:

RewriteRule ^news/([0-9]+)/([0-9a-zA-Z_-]+) article.php?id=$1&title=$2 [NC,L]

将php更改为此可以解决问题:

RewriteRule ^article/([0-9]+)/([0-9a-zA-Z_-]+) article.php?id=$1&title=$2 [NC,L]

此外,我html中的php代码必须以与我在.htaccess文件中写的格式相同的格式重写

再次相同,而不是:

<a class="brand-text" href="article?id=<?php echo $pizza['id']?>&title=<?php echo ($pizza['slug'])?>">

我将其更改为

 <a class="brand-text" href="article/<?php echo $pizza['id']?>/<?php echo ($pizza['slug'])?>">

希望这对以后的人有帮助