Apache URL重写/重定向与数据库数据

时间:2015-05-19 12:03:03

标签: php apache .htaccess mod-rewrite redirect

这是我的PHP代码(qs.php)。此文件包含漂亮的URL链接。

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

此链接会显示此链接 - http://localhost/qs1/12345678

QS1是一个php文件(qs1.php)。

到目前为止,下面是htaccess文件。

RewriteEngine On
RewriteBase /

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

在qs1.php文件中,我通过var1获取查询字符串$_GET['var1']

我想通过此网址http://localhost/qs1/12345678访问链接。 如果用户在此末尾添加斜杠http://localhost/qs1/12345678/,则页面会将其自身重定向到此http://localhost/qs1/12345678

目前我在打开此http://localhost/qs1/12345678/

时收到错误404

感谢您的评论。

1 个答案:

答案 0 :(得分:3)

您的规则不匹配,因为它在数字
之后等待其他内容 例如http://example.com/qs1/12345678/something

您可以在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]