且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在php中将查询字符串转换为斜杠URL?

更新时间:2023-02-19 12:27:50

转换在这里不是一个名词。

Convert is not a got term here.

与htaccess有关的问题是,请求应如何处理来自浏览器的 。如果您希望来自浏览器的请求看起来像 http://example.com/projectname/api/login ,但在内部应该执行 http: //example.com/projectname/api/index.php?type=login 称为 rewrite

The question with htaccess in your case is, what should happen with a request that is coming from a Browser. If you like that a request from the browser looks like http://example.com/projectname/api/login but internally it should do http://example.com/projectname/api/index.php?type=login than this is called rewrite.

另一个选项是您想要一个 redirect (重定向),这表示浏览器是否在请求例如 http://example.com/projectname/api/login 服务器使用正确的URL进行响应,例如 http://example.com/projectname/api/index.php?type=login ,浏览器现在即刻加载此页面。如果您在浏览器中对此进行了测试,您将看到URL将会更改。

The other option is that you want to have a redirect, that means if a browser is requesting e.g. http://example.com/projectname/api/login the server respond with the correct URL e.g. http://example.com/projectname/api/index.php?type=login and the browser now loading this page instant. If you test this in your Browser you will see that the URL will change.

因此,对于内部重写,您可以使用以下代码:

So for a internal rewrite you can use this:

RewriteEngine On
# Rewrite from e.g. /projectname/api/login to /projectname/api/index.php?type=login
RewriteRule ^/?projectname/api/(.*)$ /projectname/api/index.php?type=$1 [QSA,L]

要进行重定向

RewriteEngine On
# Redirect from e.g. /projectname/api/login to /projectname/api/index.php?type=login
RewriteRule ^/?projectname/api/(.*)$ /projectname/api/index.php?type=$1 [R=301,QSA,L]

这将重定向或重写,例如 / projectname / api / login /projectname/api/index.php?type=login / projectname / api / logout /projectname/api/index.php?type=logout

This will redirect or rewrite e.g /projectname/api/login to /projectname/api/index.php?type=login or /projectname/api/logout to /projectname/api/index.php?type=logout

核心这也可能是另一种方式进行重写:

Of core this is is also possible the other way around for rewrite:

RewriteEngine On
# Rewrite from e.g. /projectname/api/index.php?type=login to /projectname/api/login
RewriteCond %{QUERY_STRING} ^type=([^&]*)$
RewriteRule ^/?projectname/api/index.php$ /projectname/api/%1 [L]

也用于重定向

RewriteEngine On
# Redirect from e.g. /projectname/api/index.php?type=login to /projectname/api/login
RewriteCond %{QUERY_STRING} ^type=([^&]*)$
RewriteRule ^/?projectname/api/index.php$ /projectname/api/%1 [R=301,L]





如果您有一些HTML输出,并且想要在将输出提供给浏览器之前对其进行更改 ,. htaccess将无济于事,您必须在您的PHP应用程序中完成此操作。

But

If you have some HTML output and you want to change the output before it is served to the browser, .htaccess could not help you, you have to do it in your PHP application.