重写URL,404文件未找到

huangapple go评论56阅读模式
英文:

Rewrite URL , 404 File not found

问题

我试图从URL中删除2个文件夹路径,但无法使其工作。
我的URL看起来像这样:http://example.com/files/uploads/PP/test.pdf
我想要从URL中删除/files/uploads,以便只剩下http://example.com/PP/test.pdf

我的重写规则如下:

RewriteBase /files/uploads/
RewriteRule ^files/uploads/(.*) /$1 [NC,L,R=302]

URL被重写为http://example.com/PP/test.pdf,但它显示文件不存在。
我该如何修复这个问题?

英文:

I am trying to remove 2 folders path from the URL but I cant get that to work.
My URL looks like this: http://example.com/files/uploads/PP/test.pdf
I would like to remove the /files/uploads from the URL so that I remain only with http://example.com/PP/test.pdf.

My Rewrite rule looks like this:

RewriteBase /files/uploads/
RewriteRule ^files/uploads/(.*) /$1 [NC,L,R=302]

The URL gets rewrited in http://example.com/PP/test.pdf but it says that the file does not exist.
How can I do fix this?

答案1

得分: 1

你不使用.htaccess来实际“更改”URL。你使用.htaccess来允许“更改后”的URL起作用。首先必须在你的内部链接(在你的HTML源代码中)中更改URL。

(另外:你可以稍后实施一个额外的重定向,将“旧”的URL重定向到“新”的URL,以改善SEO,但这是次要的,不是使其“起作用”所必需的。而且由于这是一个.pdf文件,可能并不是一个关注点。这就是你尝试用你发布的“重定向”来做的事情。)

所以,假设实际文件位于/files/uploads/PP/test.pdf,而你正在链接到/PP/test.pdf(新的规范化URL),那么你可以在根.htaccess文件的顶部使用以下代码将从/PP/test.pdf发起的请求在内部重写为/files/uploads/PP/test.pdf

RewriteEngine On

RewriteRule ^PP/test\.pdf$ files/uploads/$0 [END]

其中$0是一个反向引用,包含RewriteRule模式中的整个匹配,即在本例中是PP/test.pdf

要匹配任何一个路径段深度为一个的.pdf URL(即/<path-segment>/<file>.pdf),则相应地修改RewriteRule模式。例如:

RewriteRule ^[^/]+/[^/]+\.pdf$ files/uploads/$0 [END]

参考:

英文:

You don't use .htaccess to actually "change" the URL. You use .htaccess to allow the "changed" URL to work. The URL must first be changed in your internal links (in your HTML source).

(Aside: You can later implement an additional redirect to redirect the "old" URL to the "new" URL - for the benefit of SEO - but that is secondary and not required to get this to "work". And since this is a .pdf file then that may not be a concern anyway. This is what you are trying to do with the "redirect" you have posted.)

So, asssuming the actual file is located at /files/uploads/PP/test.pdf and you are linking to /PP/test.pdf (the new canonical URL) then you would use the following at the top of the root .htaccess file to internally rewrite requests from /PP/test.pdf back to /files/uploads/PP/test.pdf:

RewriteEngine On

RewriteRule ^PP/test\.pdf$ files/uploads/$0 [END]

Where $0 is a backrefence that contains the entire match from the RewriteRule pattern. ie. PP/test.pdf in this case.

To match any .pdf URL that is one path-segment deep (ie. /&lt;path-segment&gt;/&lt;file&gt;.pdf) then modify the RewriteRule pattern accordingly. For example:

RewriteRule ^[^/]+/[^/]+\.pdf$ files/uploads/$0 [END]

Reference:

huangapple
  • 本文由 发表于 2023年4月4日 16:30:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定