douhuai2861 2014-09-30 17:32
浏览 41
已采纳

.htaccess重写:规则相同,位置不同

Below is a list of some rewrite rules that I want to have for my index page:

www.website.com/index.php?page=page1 -> www.website.com/page1
www.website.com/index.php?page=page2 -> www.website.com/page2

But I also have a profile page where I want the following rules:

www.website.com/profile.php?user=user1 -> www.website.com/user1
www.website.com/profile.php?user=user2 -> www.website.com/user2

Both use the same rule, but have different locations. For the index page, there are only 2 possible parameters, page1 and page2, but the profile page's parameters can be anything.

How can I achieve these rewrite rules without doing something like www.website.com/page/page1 and www.website.com/user/user1. I need those exact rules as shown above.

My thought is adding a rule (I'm not sure how) above the user rules to check that the URL doesn't have page1 or page2.

  • 写回答

1条回答 默认 最新

  • duanji1902 2014-09-30 17:40
    关注

    Since you only have 2 possible pages, you can get away with something like this:

    RewriteEngine On
    
    RewriteRule ^(page1|page2)$ /index.php?page=$1 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)$ /profile.php?user=$1 [L]
    

    If you need to redirect externally as well, add these (right below RewriteEngine On):

    RewriteCond %{THE_REQUEST} \ /+index\.php\?page=(page1|page2)
    RewriteRule ^ /%1? [L,R]
    
    RewriteCond %{THE_REQUEST} \ /+profile\.php\?user=([^&\ ]+)
    RewriteRule ^ /%1? [L,R]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗