简体   繁体   中英

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

The problem I'm having is the $_GET method is not recognizing the slug, so it's giving me a 404 error. The slug is definitely in my database. I'm not sure why I cannot retrieve it.

Below is my htaccess code and my php code to call the page.

Htaccess Code:

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

//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. Change that to ([A-Za-z0-9-]+) and add [L] to the end of that line.

Also, for the sake of doing things properly, remove the second and third calls to 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:

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

That should change your url to https://mywebsite.com/pretty-url.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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