简体   繁体   中英

How to rename part of a url with .htaccess?

I currently have very little Apache experience, and am having difficulties with my .htaccess file. My question is this: how can I rename these files, listed below, properly? I believe my syntax is accurate, according to http://www.htaccesscheck.com , but when accessing these pages, either A: the page won't load due to a redirect loop, or B: the page won't load, but will redirect to the wrong page. Here is my current .htaccess file for this directory:

RewriteEngine On
RewriteBase /photos/

RewriteRule ^(.*)-(.*)$ archives.php?month=$1&year=$2 [L]

RewriteRule ^(.*)$ catpost.php?id=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.*)$ viewpost.php?id=$1 [QSA,L]

Any help is much appreciated.

Try code below:

RewriteEngine on
RewriteBase /photos/

RewriteRule ^([0-9]{1,2})-([0-9]{4})$ archives.php?month=$1&year=$2 [L]

RewriteRule ^([0-9]+)$ catpost.php?id=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.*)$ viewpost.php?id=$1 [QSA,L]

This rules will check, if:

  • request like yourdomain/11-1111, then return archives.php
  • request like yourdomain/111, then return catpost.php (you can type any number)
  • else will return viewpost

You have some errors in your current .htaccess, because your second rule get result of first rule.

By the way, you can use http://htaccess.madewithlove.be/ to check step by step what is posted to your rewrite rules.

be sure to write a valid pattern
try this

RewriteEngine On
RewriteBase /photos/

RewriteRule ^(.*?)-(.*?)$ archives.php?month=$1&year=$2 [L]

RewriteRule ^(.*?)$ catpost.php?id=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.*?)$ viewpost.php?id=$1 [QSA,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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