简体   繁体   中英

Apache mod_rewrite: rewrite a path into a query string of an existing file

I am creating a simple redirect tool for myself in PHP. I'm going to store codes that map to their respective URLs in an associative array, and then redirect anybody who inputs this code to their URL.

I am using query strings to GET the input (the name of the variable and the value, which is the code), and I already know how to make the redirect part work with PHP. The issue is, I don't want my users to have to type in a question mark, the name of the variable, and then an equals sign. I would like for them to simply type in a path that will be converted into a query string, so that PHP can process the redirection.

I was wondering how I could turn a path (an arbitrary URL path) into a query string of an existing file. I was able to find the opposite task quite easily on Stack Overflow ( .htaccess - Rewrite query string and redirect to directory ) but I want to be able to pass any arbitrary URL path (that does not exist in the directory) into an existing file's query string. I found an example of what I wanted ( URL rewrite for converting path to querystring ), but it was for multiple query strings and in this case, I only need one. I don't think the last question I referenced was successfully answered either.

How can I redirect

https://www.example.com/r/blahblahblah

into

https://www.example.com/r/index.php?r=blahblahblah

using .htaccess, so that I can parse the query string in my PHP file?

Something like this:

RewriteRule ^(.*)$ index.php?r=$1 [NC,L,QSA]

On this URL:

example.com/r/blahblahblah

From index.php:

print_r($_GET);

Will return this:

Array ( [r] => blahblahblah )

(Edit to mention this assumes .htaccess is in the /r directory)

RewriteEngine On
RewriteRule ^r/([a-zA-Z0-9]+)$ /r/index.php?r=$1

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