# Activitat pràctica: Introducció a `mod_rewrite` **Entorn: Ubuntu + Apache2** ## Entorn de treball - Sistema operatiu: **Ubuntu** - Servidor web: **Apache2** - Ruta del projecte: `/var/www/html/activitat` - URL: `http://localhost/activitat` ## Nota important: Aquesta pràctica conté errors intencionats, la detecció dels errors és clau per al funcionament i la correcció de l'activitat. ## 1 Preparació de l’entorn ### 1.1 Crear el directori del projecte ```bash sudo mkdir -p /var/www/html/activitat sudo chown -R $USER:www-data /var/www/html/activitat ``` ### 1.2 Crear els fitxers ```bash cd /var/www/html/activitat nano index.html nano producte.php nano error404.html ``` **index.html** ```html <h1>Benvinguts</h1> <a href="/activitat/producte/7">Producte 7</a><br> <a href="/activitat/v1/contacte.html">Contacte antic</a> ``` **producte.php** ```php <?php echo "<h1>Producte ID: " . $_GET['id'] . "</h1>"; ``` **error404.html** ```html <h1>Error 404</h1> <p>Pàgina no trobada</p> ``` --- ## 2 Activar `mod_rewrite` ### 2.1 Activar el mòdul ```bash sudo a2enmod rewrite ``` ### 2.2 Permetre l’ús de `.htaccess` Edita el fitxer: ```bash sudo vim /etc/apache2/apache2.conf ``` Busca: ```apache <Directory /var/www/> AllowOverride None ``` Canvia-ho per: ```apache <Directory /var/www/> AllowOverride All </Directory> ``` ### 2.3 Reiniciar Apache ```bash sudo systemctl restart apache2 ``` --- ## 3 Part A — URLs amigables ### Objectiu Fer que aquesta URL: ``` http://localhost/activitat/producte/7 ``` carregui internament: ``` producte.php?id=7 ``` ### Crear el fitxer `.htaccess` ```bash vim /var/www/html/activitat/.htaccess ``` **Contingut:** ```apache RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^producte/([0-9]+)$ activitat/producte.php?id=$1 [L] ``` --- ## 4 Part B — Redirecció 301 ```apache RewriteRule ^v1/contacte\.html$ /activitat/contacte.html [R=301,L] ``` --- ## 5 Part C — Bloqueig de fitxers sensibles ```apache RewriteRule \.(bak|old)$ - [F,L] ``` --- ## 6 Part D — Depuració Desactiva temporalment `RewriteEngine On` i observa el comportament.
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up