Htaccess Mod Rewrite不适用于漂亮网址

时间:2016-05-31 23:20:22

标签: apache .htaccess mod-rewrite

我觉得这样的工具不得不发布这个问题,但对于我的生活,我无法弄清楚如何解决我的问题。 (我也读过/试过以前的帖子,但没有人帮助我)

我正在尝试将https://mywebsite.com/article.php?slug=pretty-url转为https://mywebsite.com/article/pretty-url

我遇到的问题是$_GET方法无法识别slug,所以它给了我404错误。 slug肯定在我的数据库中。我不知道为什么我无法找回它。

下面是我的htaccess代码和我的php代码来调用页面。

Htaccess代码:

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

# Redirect www urls to non-www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.mywebsite\.com [NC]
RewriteRule (.*) https://mywebsite.com/$1 [L]

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://mywebsite.com/$1 [L]

ErrorDocument 404 /404.php

#Pretty URL for Blog
RewriteRule ^article/([0-9a-zA-Z]+) article.php?slug=$1


#Rewrite for certain files with .php extension
RewriteRule ^about$ about.php
RewriteRule ^services$ services.php
RewriteRule ^portfolio$ portfolio.php
RewriteRule ^blogs$ blogs.php
RewriteRule ^tutorials$ tutorials.php
RewriteRule ^contact$ contact.php
RewriteRule ^privacy-policy$ privacy-policy.php
RewriteRule ^terms-of-service$ terms-of-service.php
RewriteRule ^sitemap$ sitemap.php
</IfModule>

在article.php页面上的PHP代码:

//Get the blog. Only blogs that are published
$slug = $_GET['slug'];
$publish = intval(1);

//Query the database
$sql =  "SELECT * FROM blogs WHERE publish = $publish AND slug = $slug";   


//Execute the query
$stmt = $db->query($sql); 
$row = $stmt->fetch(PDO::FETCH_ASSOC);

2 个答案:

答案 0 :(得分:1)

([0-9a-zA-Z]+)无法捕获pretty-url,因为该群组不允许使用连字符。将其更改为([A-Za-z0-9-]+)并将[L]添加到该行的末尾。

另外,为了正确处理,请删除对RewriteEngine On的第二次和第三次调用。

答案 1 :(得分:0)

永远不要为一个问题道歉!如果您遇到困难,我们会尽力提供帮助。

您在htaccess中需要的是以下内容:

RewriteEngine On
RewriteRule ^([^/]*)\.html$ /article.php?slug=$1 [L]

这应该将您的网址更改为https://mywebsite.com/pretty-url.html

相关问题