简体   繁体   English

如何在htaccess Apache中将/en/file.php转换为file.php?lang = en

[英]How to translate /en/file.php to file.php?lang=en in htaccess Apache

I'm writing multilingual website. 我正在写多语言网站。 I have several files on server like: 我在服务器上有几个文件,例如:

/index.php
/files.php
/funny.php

And would like to add language support by placing language code into URL like this: 并希望通过将语言代码放入URL中来添加语言支持,如下所示:

http://mywebsite/en/index.php

would redirect to: 将重定向到:

http://mywebsite/index.php?lang=en

And

http://mywebsite/en/files.php

would redirect to: 将重定向到:

http://mywebsite/files.php?lang=en

I would like to put more languages for example: 我想举例说更多的语言:

http://mywebsite/ch-ZH/index.php

And I would like this to work only for files with php and php5 extension. 我希望这仅适用于具有php和php5扩展名的文件。 Rest of files should be the same as they are. 其余文件应与它们相同。

So for example when i will go to address 因此,例如,当我要去地址时

http://mywebsite/ch-ZH/index.php

I would like my PHP to recognize that current path is 我希望我的PHP能够识别当前路径是

http://mywebsite

and NOT 并不是

http://mywebsite/ch-ZH

It's necessary for me because in my PHP code I relate on current path and would like them to work as they are working now. 这对我来说是必要的,因为在我的PHP代码中,我涉及当前路径,并希望它们在现在正常工作。

Could you please write how to prepare htaccess file on Apache to meet this criteria? 您能否写出如何在Apache上准备htaccess文件以满足这个条件?

Try this: 尝试这个:

RewriteEngine on
RewriteRule ^([a-z]{2}(-[A-Z]{2})?)/(.*) $3?lang=$1 [L,QSA]

And for the current path problem, you have to know how relative URIs are resolved: Relative URIs are resolved by the client from a base URI that is the URI ( not filesystem path! ) of the current resource if not declared otherwise. 对于当前路径问题,您必须知道如何解析相对URI:相对URI 由客户端从基本URI解析,该基本URI是当前资源的URI( 不是文件系统路径! ),除非另外声明。

So if a document has the URI /en/foo/bar and the relative path ./baz in it, the client resolves this to /en/foo/baz (as obviously the client doesn't know about the actual filesystem path). 因此,如果文档中包含URI /en/foo/bar和相对路径./baz ,则客户端 ./baz其解析为/en/foo/baz (显然,客户端不知道实际的文件系统路径)。
For having ./baz resolved to /baz , you have to change the base URI which can be done with the HTML element BASE . 为了将./baz解析为/baz ,您必须更改基本URI,这可以通过HTML元素BASE

Something like this should do the trick, 这样的事情应该可以解决问题,

RewriteEngine on
RewriteRule ^(.[^/]+)/(.*).php([5])?$ $2.php$3?lang=$1 [L]

This will only match .php and .php5 files, so the rest of your files will be unaffected. 这只会匹配.php和.php5文件,因此其余文件不会受到影响。

如果不想使用ModRewrite,可以将符号链接放在Web文件夹( ln -s . en )中,并检查PHP中的URL。

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

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