【问题标题】:Htaccess Mod Rewrite Not working for Pretty URLHtaccess Mod Rewrite 不适用于漂亮的 URL
【发布时间】:2016-05-31 23:20:22
【问题描述】:

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

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

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

下面是我的 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);

【问题讨论】:

  • 尝试将 SQL 更改为 "SELECT * FROM blogs WHERE publish = '$publish' AND slug ='$slug'"
  • @CaelanGrgurovic 好消息是我没有得到 404,而是浏览器中带有 url 的网页,但它没有从数据库中提取任何内容。
  • 我注意到有时浏览器需要一段时间才能对 htaccess 文件生效。尝试清除缓存或切换浏览器并在那里进行测试! :)
  • @CaelanGrgurovic 问题现在是否存在于我的 htaccess 代码中?
  • 我注意到的一件事是([0-9a-zA-Z]+) 不会捕获pretty-url,因为该组不允许使用连字符。将其更改为 ([A-Za-z0-9-]+) 并将 [L] 添加到该行的末尾。另外,为了做好事,把对RewriteEngine On的第二次和第三次调用去掉。

标签: apache .htaccess mod-rewrite


【解决方案1】:

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

另外,为了做好事,把对RewriteEngine On的第二次和第三次调用去掉。

【讨论】:

    【解决方案2】:

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

    您在 htaccess 中需要的内容如下:

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

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

    【讨论】:

    • 感谢您的回复。我试图完全删除页面扩展。不添加 .html。 Mike Rockett 的评论帮助了我。感谢您尝试提供帮助。非常感谢您愿意提供帮助。 :)
    • 没问题@Soletwosole,我们总是可以写一个规则来删除.html。但是,如果问题现在得到解决,那就太好了! :)
    猜你喜欢
    • 2020-01-04
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 2010-12-06
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多