Skip to content
Advertisement

.htaccess remove URL path segments that are causing an Internal Server Error

The following .htaccess Rewrite below seems working fine if the URL is something like: example.com/news/post-1

RewriteRule ^/?news/([^/]+)/?$ article.php?slug=$1 [L,QSA]

However, if the URLs have more parameters, something like: example.com/news/post-1/comment-page-1 (URLs from another version of the website) I will get a 500 Internal Server Error.

How I can make it redirect to the related post instead of 500 Internal Server Error?

Advertisement

Answer

if the URLs have more parameters, something like: example.com/news/post-1/comment-page-1 (URLs from another version of the website) I will get a 500 Internal Server Error.

That 500 error is caused by something else in your .htaccess file since the directive you posted would not apply (as stated by @CBroe in comments).

So, the 500 error could potentially be resolved by fixing whatever directive is causing this.

Incidentally, these are “path segments”, not “parameters”. You might see them as parameters to your script, but that’s not what they are in the URL being requested.

How I can make it redirect to the related post instead of 500 Internal Server Error?

If you want to resolve this by redirecting /news/<slug>/<anything> to /news/<slug>/ then you could do something like the following near the top of your .htaccess file, before the existing rewrites:

# Remove additional path segments from the URL-path
RewriteRule ^(news/[^/]+/). /$1 [R=302,L]

The dot on the regex matches a single character after the last slash, so must therefore contain an additional path segment (at least).

The $1 backreference contains just the part of the URL-path you are interested in (ie. /news/<slug>/) and redirects to this.

Note that this is currently a 302 (temporary) redirect. Always test with 302s to avoid potential caching issues before changing to a 301 (permanent) redirect once you have confirmed it works as intended.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement