简体   繁体   中英

Apache URL rewrite/redirection with database data

Here is my php code(qs.php). This file contain pretty url links.

<html>
<head></head>
<body>
    <?php  
    $file = 'qs1'; //this is a php file qs1.php
    $id = '12345678'; //testing ID
    $complete_url = $file."/".$id;

    ?>
    <a href ="<?php echo $complete_url;?>"> This is a test link </a>

</body></html>

This link appear link this - http://localhost/qs1/12345678

QS1 is a php file (qs1.php).

Below is the htaccess file so far.

RewriteEngine On
RewriteBase /

RewriteRule ^([^/]+)/(\d+)/([^/]+)$ $qs1.php?var1=$2 [NC,L]

In qs1.php file i am getting query string var1 by $_GET['var1']

I want link can be accessible by this url http://localhost/qs1/12345678 . and if user put slash at the end like this http://localhost/qs1/12345678/ then page redirect itself to this http://localhost/qs1/12345678 .

At the moment i am getting error 404 while opening this http://localhost/qs1/12345678/

Thanks for your comment.

Your rule does not match since it waits for something else after digits
eg http://example.com/qs1/12345678/something

You can use this code in your htaccess

Options -MultiViews

RewriteEngine On
RewriteBase /

# we don't touch existing files/folders
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# remove trailing slash (for instance: redirect /qs1/12345678/ to /qs1/12345678)
RewriteRule ^([^/]+)/(\d+)/$ $1/$2 [R=301,L]

# rewrite /xxx/12345 to /xxx.php?var1=12345 (if xxx.php exists)
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^([^/]+)/(\d+)$ $1.php?var1=$2 [L]

# rewrite /xxx/12345/something to /xxx.php?var1=12345&var2=something (if xxx.php exists)
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^([^/]+)/(\d+)/([^/]+)$ $1.php?var1=$2&var2=$3 [L]

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