简体   繁体   English

Htaccess Mod 重写不适用于漂亮的 URL

[英]Htaccess Mod Rewrite Not working for Pretty URL

I feel like such a tool for having to post this question, but for the life of me, I cannot figure out how to resolve my issue.我觉得这是一个不得不发布这个问题的工具,但对于我的生活,我无法弄清楚如何解决我的问题。 (I've also read/tried previous posts but none have helped me) (我也读过/尝试过以前的帖子,但没有一个对我有帮助)

I'm trying to turn https://mywebsite.com/article.php?slug=pretty-url to https://mywebsite.com/article/pretty-url我正在尝试将https://mywebsite.com/article.php?slug=pretty-url 转换https://mywebsite.com/article/pretty-url

The problem I'm having is the $_GET method is not recognizing the slug, so it's giving me a 404 error.我遇到的问题是$_GET方法无法识别 slug,所以它给了我一个 404 错误。 The slug is definitely in my database. slug 肯定在我的数据库中。 I'm not sure why I cannot retrieve it.我不知道为什么我无法检索它。

Below is my htaccess code and my php code to call the page.下面是我的 htaccess 代码和我调用页面的 php 代码。

Htaccess Code: 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>

PHP Code on the article.php page: 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);

([0-9a-zA-Z]+) will not capture pretty-url because the group doesn't allow for hyphens. ([0-9a-zA-Z]+)不会捕获pretty-url因为该组不允许使用连字符。 Change that to ([A-Za-z0-9-]+) and add [L] to the end of that line.将其更改为([A-Za-z0-9-]+)并将[L]添加到该行的末尾。

Also, for the sake of doing things properly, remove the second and third calls to RewriteEngine On .另外,为了正确处理,删除第二次和第三次对RewriteEngine On调用。

Never apologise for a question!永远不要为一个问题道歉! If you're stuck, we will try to help.如果您遇到困难,我们会尽力提供帮助。

What you need in your htaccess is the following:您在 htaccess 中需要的是以下内容:

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

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

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

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