简体   繁体   English

使用 .htaccess 和 php 重写 url 不使用连字符“-”

[英]Rewrite url not working with hyphen “-” using .htaccess with php

I'm trying to make my url user-friendly by using .htaccess rewrite.我试图通过使用 .htaccess 重写使我的 url 用户友好。

from url - http://localhost/Web/new_products.php?cat_id=1&cat_title=new-rocket从 url - http://localhost/Web/new_products.php?cat_id=1&cat_title=new-rocket

to url - http://localhost/Web/new-rocket-1.php到 url - http://localhost/Web/new-rocket-1.php

in my new_products.php在我的 new_products.php

$get_cat = "select * from new_products_cat";
$run_cat = mysqli_query($con, $get_cat);
while($row_cat = mysqli_fetch_array($run_cat)){
                    
$cat_id = $row_cat['cat_id'];
$cat_title = $row_cat['cat_title'];
$hyphen_cat_title = str_replace(' ', '-', $cat_title);
                    
echo "
<a href='new_products.php?cat_id=$cat_id&cat_title=$hyphen_cat_title'>
......
......
......

in my .htaccess在我的 .htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{THE_REQUEST} /Web/new_products.php\?cat_id=([^&\s]+)&cat_title=([^&\s]+) [NC]  
    RewriteRule ^ /Web/%2-%1\.php? [NC,R,L,NE]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^-]+)-([^.]+)\.php$ /Web/new_products.php?cat_id=$2&cat_title=$1 [QSA,L,NC]
</IfModule>

Question 1问题 1

My code working only if i use "underscore".我的代码只有在我使用“下划线”时才有效。 $hyphen_cat_title = str_replace(' ', '_', $cat_title); $hyphen_cat_title = str_replace(' ', '_', $cat_title);

But not working if i use "hyphen", its keep redirecting to http://localhost/Web/new_products.php但如果我使用“连字符”则不起作用,它会继续重定向到 http://localhost/Web/new_products.php

Question 2问题2

Can i replace "space" to "hyphen" using rewrite in .htaccess?我可以在 .htaccess 中使用重写将“空格”替换为“连字符”吗? without using php str_replace不使用 php str_replace

For my Question 1对于我的问题 1

The problem was [^-] “every character but a hyphen”.问题是 [^-] “除了连字符之外的每个字符”。 Thanks to @CBroe感谢@CBroe

Below code fixed my problem.下面的代码解决了我的问题。

RewriteRule ^([^.]+)-([^.]+)\.php$ /Web/new_products.php?cat_id=$2&cat_title=$1 [QSA,L,NC]

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

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