php + .htaccess issue when rewriting urls for pretty permalinks

44 Views Asked by At

I'm trying to make a very simple small app in php: it is a small caption system for a museum. The structure is an so an index.php file that sends requests via querystring to a details.php page where I can read the single caption.

I'll preface this by saying that I know little about servers and routing so I'm definitely missing something simple.I've tried watching every tutorial imaginable but I can't figure out what's not working.

I am developing locally on MAMP: basic rewrites are working but my solution doesn't.

This is the markup for the index:

<!DOCTYPE html>
<html lang="en">

<?php include('includes/header.php'); ?>

<?php foreach($didas as $dida):  ?>

    <h3><?php echo htmlspecialchars($dida['title']); ?></h3>

    <a href = "details/details.php?url=<?php echo($dida['url']) ?>" >link</a>;

<?php endforeach ?>

<?php include('includes/footer.php'); ?>

</html>

The database is a table with 4 columns in mySql. one these columns is the url parameter which ideally becomes the querystring that calls the caption to me.

The url with the querystring is something like this:

http://localhost:8888/dida/details/details.php?url=test-1

and I am trying to rewrite it like this:

http://localhost:8888/dida/details/test-1

And here is my problem:

I tried to change this url with .htaccess: I followed a lot of different tutorials and answers here on stackoverflow

This is my Htaccess code


RewriteEngine On

# this rule rewrites my url but it gives me a 404 error

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^url=([\w/-]*)
RewriteRule ^details/details\.php$ /dida/details/%1 [QSD,R=302,L]

EDIT: for all of you wondering thanks to the heads up by @CBroe. The problem is that I completely misunderstood how rewrites work

I had to create the link in index.php in the output format I wanted to have and THEN redirect that url to the request with the querystring in the right format.

So: Index.php now is this

<!DOCTYPE html>
<html lang="en">

<?php include('includes/header.php'); ?>

<?php foreach($didas as $dida):  ?>

    <h3><?php echo htmlspecialchars($dida['title']); ?></h3>

    **<a href = "details/details.php?url=<?php echo($dida['url']) ?>" >link</a>;**

<?php endforeach ?>

<?php include('includes/footer.php'); ?>

</html>

and the .htaccess is this:

RewriteEngine On

# Redirect incoming requests from /dida/details/xy to details/details.php?url=xy
RewriteCond %{ENV:REDIRECT_STATUS} ^$
**RewriteRule ^dida/details/([\w/-]+)$ /dida/details/details.php?url=$1 [QSD,L]**

1

There are 1 best solutions below

0
Deen On

You can try this a simple .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Hope this help you.

You can learn more about it https://github.com/phanan/htaccess