简体   繁体   English

如何在.htaccess中编写mod_rewrite规则

[英]how to write mod_rewrite rule in .htaccess

I am in the process of redirecting some urls to specific page using mod_rewrite in htaccess file. 我正在使用htaccess文件中的mod_rewrite将一些URL重定向到特定页面。 The project is developed in core PHP(no frameworks) and i'm working on xampp server, 该项目是在核心PHP(无框架)中开发的,并且我正在xampp服务器上工作,

Ex: I want the following url to be redirected to test.php 例如:我想将以下网址重定向到test.php

localhost/project/any_string //should be redirected to test.php
localhost/project/any_string/test //should be redirected to new_test.php

And

localhost/project/any_string.php //should be redirected to any_string.php only
localhost/project/any_string/any_string.php //should be redirected to any_string/any_string.php only

I have mod_rewrite enabled, any help would be appreciated. 我启用了mod_rewrite,任何帮助将不胜感激。

If I understand what you need, this will do it: 如果我了解您的需求,那么可以做到:

RewriteEngine On
RewriteRule ^(.*)project/(.*)/(.*).php$ /$2/$3.php [L,R=301]
RewriteRule ^(.*)project/(.*).php$ /$2.php [L,R=301]
RewriteRule ^(.*)project/(.*)test$ /new_test.php [L,R=301]
RewriteRule ^(.*)project/(.*)$ /test.php [L,R=301]

By the way, the order of the rules here is very important, so you have to keep it exactly the same. 顺便说一句,这里的规则顺序非常重要,因此您必须使其完全相同。

Are you looking for something like the following? 您是否正在寻找类似以下的内容?

RewriteEngine On
RewriteRule localhost/project/(.*)/test new_test.php [R]
RewriteRule localhost/project/(.*) test.php [R]
RewriteRule localhost/project/(.*)/(.*).php $1/$2.php [R]
RewriteRule localhost/project/(.*).php $1.php [R]

The [R] flag forces a Redirect. [R]标志强制重定向。 Note that longer matches are listed before shorter ones (otherwise the longer matches would never be matched.) 请注意,较长的匹配项将在较短的匹配项之前列出(否则,较长的匹配项将永远不会被匹配。)

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

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