SEO友好的URL与.htaccess

时间:2016-09-11 15:38:34

标签: apache .htaccess mod-rewrite

在发布此内容之前,请浏览一下,找不到与我的具体问题相符的任何内容。

在我的网站上,我更喜欢我的网址没有.php,所以我已经在我的.htaccess文件中设置了它并且它完美无缺。目前,我的网站上有一个名为“相册”的页面,这是当前年度最佳专辑。不过,我也希望明年能够这样做,等等。现在,我可以将它作为专辑吗?date = 2017,但这看起来很难看。我想把它作为example.com/albums/2017来做,因为它看起来好多了,而且更加SEO友好。

我在HTACCESS中的内容如下:

RewriteEngine On

# Remove PHP from file names
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]

# Redirect albums.php?date=2017 to albums/2017
RewriteCond %{THE_REQUEST} \s/albums\?date=([0-9]+)\s [NC]
RewriteRule ^ /albums/%1? [R=301,L]
RewriteRule ^albums/([0-9]+)$ /albums?date=$1 [L]


Options -Indexes

# Error Document Redirects
ErrorDocument 403 http://example.com/errors/403
ErrorDocument 404 http://example.com/errors/404

albums.php?date = 2017在没有重定向的情况下工作,但是当我将重定向放入时,它会将您发送到/ albums / 2017,但不会在页面上显示任何内容。如果我删除了“从文件名中删除PHP”重定向,它会显示页面上的信息。显然我已经知道错误是由于文件中的“从文件名中删除PHP”部分引起的,我只是不确定如何解决它。

我对.htaccess和RewriteEngine知之甚少,只知道足够或非常基本的东西,如果这看起来很可怕,那么道歉。我已经试着确保我没有提出重复问题,但如果我有,请抱歉,

2 个答案:

答案 0 :(得分:0)

尝试这样,

RewriteEngine On
# removed .php extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([\w-]+)$ $1.php

# you can directly use album/(date) in your url using this rule
RewriteCond %{REQUEST_FILENAME}.php !-f
RewriteCond %{REQUEST_FILENAME}.php !-d
RewriteRule ^([\w-]+)/([\d]+)$ $1.php?date=$2

答案 1 :(得分:0)

想出来。

# Redirect albums.php?date=2017 to albums/2017
RewriteRule ^albums/([^/]*)$ /albums?date=$1 [L]

# Remove PHP from file names
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]