【问题标题】:url rewriting using htaccess for single files in html and javascript使用 htaccess 重写 html 和 javascript 中的单个文件的 url
【发布时间】:2017-03-27 07:59:19
【问题描述】:

我的第一个问题是“我可以使用 html 文件来重写 url 参数并在 javascript 中处理参数吗?”

第二个问题是: 我该怎么办?,如果我想重写这些网址:

*localhost OR sample.com*/blog.html
*localhost OR sample.com*/about.html
*localhost OR sample.com*/articles.html?title=sample-name-parameter

到这些网址:

*localhost or sample.com*/blog/
*localhost or sample.com*/about/
*localhost or sample.com*/articles/sample-name-parameter

这是我的 htaccess 文件:

DirectoryIndex blog.html index.html

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.html
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^articles/([^/]+)$ /articles/$1.html?p=$2 [L]
</IfModule>

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting url-parameters


    【解决方案1】:

    其实你不能,但你可以通过分割当前路径来做到这一点,用window.location.pathname获取当前路径使用split和平分割路径。

    var path = window.location.pathname, // "/article/something"
        peaces = path.split(),
        title = peaces[1]; // "something"
    

    试试这个 htaccess 代码:

    DirectoryIndex blog.html index.html
    
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^([^/]+)/$ $1.html
    RewriteRule ^articles/([^/]+)$ /articles/articles.html?title=$1 [L]
    </IfModule>
    

    【讨论】:

    • 其实我之前试过了,但是根本没用 apache服务器显示这个错误:“在这个服务器上找不到请求的URL /articles/articles.html。”
    • 那么你在文章文件夹中的 article.html 文件丢失了,只需从 htaccess 代码中删除 RewriteRule ^articles/([^/]+)$ /articles/articles.html?title=$1 [L] 行,如果你的文件位于根目录下
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2013-04-22
    • 2017-04-08
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    相关资源
    最近更新 更多